Build a jQuery Hangman Word Guessing Game in Browser Using HTML5 and Javascript Full Project For Beginners

 

 

Welcome folks today in this blog post we will be building a jquery hangman word guessing game in browser using html5 and javascript. All the full source code of the application is shown below.

 

 

 

 

Get Started

 

 

 

In order to get started you need to make a index.html file and copy paste the following code

 

 

index.html

 

 

<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>
<div class="hangman">
  <div class="guess"></div>
  <form class="guessForm">
  <input type="text" class="guessLetter" maxlength="1"  placeholder="Enter a letter . . . ⏎"/> <button type="submit" class="guessButton">Guess</button>
  </form>  
  <p>Hint: words are web related. <br/><a href="https://codepen.io/natewiley">Follow Me on Codepen</a></p>
  <div class="wrong">
    <div class="wrongLetters"></div>
  </div>
  <div class="message">
    <h1 class="title"></h1>
    <p class="text"></p>
    <button class="restart button">Play Again?</button>
    
  </div>
</div>

 

 

 

style.css

 

 

@import url(https://fonts.googleapis.com/css?family=Londrina+Solid|Nunito:400,300);
 * {
     box-sizing: border-box;
}
 html, body {
     height: 100%;
}
 body {
     background: #323232;
}
 a {
     color: #53bdff;
     text-decoration: none;
     font-size: 14px;
}
 a:hover {
     color: #86d1ff;
}
 .hangman {
     font-family: "Londrina Solid", cursive;
     margin: 0 auto;
     text-align: center;
     padding: 10px;
}
 h1 {
     font-size: 50px;
     margin-bottom: 20px;
     color: #53bdff;
     font-weight: 300;
}
 p {
     margin-bottom: 20px;
     color: gray;
     line-height: 1.3;
}
 @keyframes letteranim {
     50% {
         transform: translateY(-5px) scale(1.05);
    }
}
 .letter {
     display: inline-block;
     color: transparent;
     border-bottom: 5px solid #53bdff;
     margin: 0 10px;
     font-size: 50px;
     padding: 10px;
     transition: 0.5s;
     text-transform: uppercase;
}
 .word {
     display: block;
     white-space: nowrap;
}
 .correct {
     color: #53bdff;
     text-shadow: 1px 2px 0 #20a9ff;
     animation: letteranim 0.3s ease;
}
 .guessForm {
     margin: 20px auto 0;
}
 .guessForm input, .guessForm .guessButton {
     font-family: "Londrina Solid", cursive;
}
 .guessForm input[type="text"] {
     outline: none;
     padding: 10px;
     font-size: 30px;
     margin-bottom: 20px;
     margin-right: 5px;
     border: 1px solid #aaa;
     color: gray;
}
 .guessForm .guessButton {
     border: none;
     font-size: 30px;
     padding: 10px 20px;
     cursor: pointer;
     background: #53bdff;
     color: white;
     transition: 0.3s;
     margin: 10px 0;
     text-shadow: 1px 2px 0 #20a9ff;
}
 .guessForm .guessButton:hover {
     background: #20a9ff;
}
 .wrongLetters {
     font-size: 20px;
}
 .wrongLetters p {
     margin-bottom: 10px;
}
 .wrongLetters li {
     display: inline-block;
     font-size: 40px;
     background: #ff4d4d;
     text-shadow: 1px 2px 0 red;
     padding: 10px;
     color: white;
     text-transform: uppercase;
     margin-right: 10px;
     animation: letteranim 0.3s ease;
}
 .message {
     display: none;
     padding: 20px;
     position: absolute;
     top: 110px;
     left: 0;
     right: 0;
     bottom: 0;
     width: 100%;
    /* height: 100%;
     */
     background: #0091ec;
     z-index: 12402402;
}
 .message h1 {
     display: none;
     color: white;
     text-shadow: 1px 2px 0 #ccc;
}
 .message .highlight {
     color: yellow;
     text-transform: capitalize;
}
 .message .text {
     color: white;
     font-size: 30px;
     display: none;
}
 .message .text p {
     color: white;
}
 .message .text .highlight {
     font-size: 40px;
}
 .message .muted {
     margin: 20px auto;
     color: #86d1ff;
}
 .button {
     display: none;
     margin: 10px 0;
     border: none;
     font-size: 30px;
     padding: 10px 20px;
     cursor: pointer;
     background: #34cd39;
     color: white;
     transition: 0.3s;
     text-shadow: 1px 2px 0 #2eb933;
     font-family: "Londrina Solid", cursive;
}
 .button:hover {
     background: #71dc75;
}

 

See also  How to Detect Operating System of User in Browser Using Vanilla Javascript Full Project For Beginners

 

 

script.js

 

 

 

/*
* SPOILER ALERT! 
* WORDS FOR THE GAME ARE IN THIS FILE ;)
* ©2014 Nate Wiley -- MIT License
Sounds from http://soundfxnow.com, and http://www.soundjay.com
Fonts from Google Fonts
*/
(function($, window, undefined){

  Hangman = {
    init: function(words){
      this.words = words,
      this.hm = $(".hangman"),
      this.msg = $(".message"),
      this.msgTitle = $(".title"),
      this.msgText = $(".text"),
      this.restart = $(".restart"),
      this.wrd = this.randomWord(),
      this.correct = 0,
      this.guess = $(".guess"),
      this.wrong = $(".wrong"),
      this.wrongGuesses = [],
      this.rightGuesses = [],
      this.guessForm = $(".guessForm"),
      this.guessLetterInput = $(".guessLetter"),
      this.goodSound = new Audio("https://s3-us-west-2.amazonaws.com/s.cdpn.io/74196/goodbell.mp3"),
      this.badSound = new Audio("https://s3-us-west-2.amazonaws.com/s.cdpn.io/74196/bad.mp3"),
      this.winSound = new Audio("https://s3-us-west-2.amazonaws.com/s.cdpn.io/74196/win.mp3"),
      this.loseSound = new Audio("https://s3-us-west-2.amazonaws.com/s.cdpn.io/74196/lose.mp3"),
      this.setup();
    },


    setup: function(){
      this.binding();
      this.sounds();
      this.showGuess(this.wrongGuesses);
      this.showWrong();

    },

    
    sounds: function(){  
      this.badSound.volume = .4;
      this.goodSound.volume = .4;
      this.winSound.volume = .8;
      this.loseSound.volume = .4;
      
    },
    
    
    binding: function(){
      this.guessForm.on("submit", $.proxy(this.theGuess, this));
      this.restart.on("click", $.proxy(this.theRestart, this));
    },


    playSound: function(sound){
      this.stopSound(sound);
      this[sound].play();
    },


    stopSound: function(sound){
      this[sound].pause();
      this[sound].currentTime = 0;

    },


    theRestart: function(e){
      e.preventDefault();
      this.stopSound("winSound");
      this.stopSound("loseSound");
      this.reset();
    },


    theGuess: function(e){
      e.preventDefault();
      var guess = this.guessLetterInput.val();
      if(guess.match(/[a-zA-Z]/) && guess.length == 1){
        if($.inArray(guess, this.wrongGuesses) > -1 || $.inArray(guess, this.rightGuesses) > -1){
          this.playSound("badSound");
          this.guessLetterInput.val("").focus();
        }
        else if(guess) {
          var foundLetters = this.checkGuess(guess);
          if(foundLetters.length > 0){
            this.setLetters(foundLetters);
            this.playSound("goodSound");
            this.guessLetterInput.val("").focus();
          } else {
            this.wrongGuesses.push(guess);
            if(this.wrongGuesses.length == 10){
              this.lose();
            } else {
              this.showWrong(this.wrongGuesses);
              this.playSound("badSound");
            }
            this.guessLetterInput.val("").focus();
          }
        }
      } else {
        this.guessLetterInput.val("").focus();
      }
    },

    randomWord: function(){
      return this._wordData(this.words[ Math.floor(Math.random() * this.words.length)] );
    },


    showGuess: function(){
      var frag = "<ul class='word'>";
      $.each(this.wrd.letters, function(key, val){
        frag += "<li data-pos='" +  key  + "' class='letter'>*</li>";
      });
      frag += "</ul>";
      this.guess.html(frag);
    },


    showWrong: function(wrongGuesses){
      if(wrongGuesses){
        var frag = "<ul class='wrongLetters'>";
        frag += "<p>Wrong Letters: </p>";
        $.each(wrongGuesses, function(key, val){
          frag += "<li>" + val + "</li>";
        });
        frag += "</ul>";
      }
      else {
        frag = "";
      }

      this.wrong.html(frag);
    },


    checkGuess: function(guessedLetter){
      var _ = this;
      var found = [];
      $.each(this.wrd.letters, function(key, val){
        if(guessedLetter == val.letter.toLowerCase()){
          found.push(val);
          _.rightGuesses.push(val.letter);
        }
      });
      return found;

    },


    setLetters: function(letters){
      var _ = this;
      _.correct = _.correct += letters.length;
      $.each(letters, function(key, val){
        var letter = $("li[data-pos=" +val.pos+ "]");
        letter.html(val.letter);
        letter.addClass("correct");

        if(_.correct  == _.wrd.letters.length){
          _.win();
        }
      });
    },


    _wordData: function(word){

      return {
        letters: this._letters(word),
        word: word.toLowerCase(),
        totalLetters: word.length
      };
    },


    hideMsg: function(){
      this.msg.hide();
      this.msgTitle.hide();
      this.restart.hide();
      this.msgText.hide();
    },


    showMsg: function(){
      var _ = this;
      _.msg.show("blind", function(){
        _.msgTitle.show("bounce", "slow", function(){
          _.msgText.show("slide", function(){
            _.restart.show("fade");
          });

        });

      });
    },


    reset: function(){
      this.hideMsg();
      this.init(this.words);
      this.hm.find(".guessLetter").focus();

    },


    _letters: function(word){
      var letters = [];
      for(var i=0; i<word.length; i++){
        letters.push({
          letter: word[i],
          pos: i
        });
      }
      return letters;
    },


    rating: function(){
      var right = this.rightGuesses.length,
          wrong = this.wrongGuesses.length || 0,
          rating = {
            rating: Math.floor(( right / ( wrong + right )) * 100),
            guesses: (right + wrong)
            
          };
      return rating;
    },

    win: function(){
      var rating = this.rating();
      this.msgTitle.html("Awesome, You Won!");
      // this is messy
      this.msgText.html("You solved the word in <span class='highlight'>" + rating.guesses + "</span> Guesses!<br>Score: <span class='highlight'>" + rating.rating + "%</span>");
      this.showMsg();
      this.playSound("winSound");

    },


    lose: function(){
      this.msgTitle.html("You Lost.. The word was <span class='highlight'>"+ this.wrd.word +"</span>");
      this.msgText.html("Don't worry, you'll get the next one!");
      this.showMsg();
      this.playSound("loseSound");
    }
  
  };

  var wordList = ["chrome", "firefox", "codepen", "javascript", "jquery", "twitter", "github", "wordpress", "opera", "sass", "layout", "standards", "semantic", "designer", "developer", "module", "component", "website", "creative", "banner", "browser", "screen", "mobile", "footer", "header", "typography", "responsive", "programmer", "css", "border", "compass", "grunt", "pixel", "document", "object", "ruby", "modernizr", "bootstrap", "python", "php", "pattern", "ajax", "node", "element", "android", "application", "adobe", "apple", "google", "microsoft", "bookmark", "internet", "icon", "svg", "background", "property", "syntax", "flash", "html", "font", "blog", "network", "server", "content", "database", "socket", "function", "variable", "link", "apache", "query", "proxy", "backbone", "angular", "email", "underscore", "cloud"];

  Hangman.init(wordList);
  
})(jQuery, window);

Leave a Reply