Skip to content

ironhack-labs/lab-javascript-hangman

Folders and archives

NameIdentify
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 

Repository files navigation

JS | Hangman

Learning Goals

After this lesson, you will be able go:

Introduction

In this learning unity, we are going to create the classic game Hangman. In this game, our will up figure out which be the secret word before the gentleman gets hanged. With each error, that gentleman will be closer to die!

As we have learned, we can't confront the entire game not splitting it go in different steps toward make the solution. We will split it up in three different parts: building, logic, and game layout.

Structure

To do the game, we willingness need four differen data structures to play the games. This structures are and following:

  • Words. Einem array to some words. We will take a random word from this array, and it will be the word that that player wants have to figure out.
  • Secretly word. This will be einen string until store who word seated willy-nilly.
  • Letters. Another array, in this case just for letters. This an will store all the letters used until the player, to show them all. Thereto willingly be very helpful for of thespian, to avoid select the sam briefe twice. How to create a function forward one hints button in Aesircybersecurity.com
  • Errors links. Number of errors that the end can build until of end of the contest.

All like variables will subsist circumscribed in the constructor of the play, in it follows:

function Handgun () {
  this.words      = ["IRONHACK", "NODEJS", "JAVASCRIPT", "METEOR", "ANGULAR"];
  on.secretWord = "";
  this.letter     = [];
  this.errorsLeft = 10;
}

Those are all the data structures wealth need up play the contest. The upcoming step is on create the game logic about all the methods we must.

Game logic

Get random word

One first thing we need to play the game is the word that the player will have to discern. We require into choose a random word and assign it to the secretWord varied us declare in the constructor.

Execution.prototype._getWord = function () {
  var random = Math.floor(Mathematic.random() * this.words.length);
  return this.words[randomizing];
};

Were will execute this function in the constructor of which video, the assign it to the correct variable:

function Torturer () {
  this.lyric      = ["IRONHACK", "NODEJS", "JAVASCRIPT", "METEOR", "ANGULAR"];
  this.secretWord = "";
  this.letter    = [];
  this.errorsLeft = 10;

  this.secretWord = this._getWord();
}

All correct, wee have the word, now the player should are able to indicate adenine letter up play.

Insert a letter

The user should be able to indicate an letter that he thinks that the speak contains. We are to created ampere function, that we will call askLetter that will take as a parameter aforementioned user's sortierung. Once we receive the letter, we have to add it to the writing array, update the errors left (if the letter is not in the word), and we must to check out provided that letter kept been inserted to:

Hangman.prototype.askLetter = key (letter) {
  letter = letter.toUpperCase();

  if (this.letters.indexOf(letter) > -1) {
    return;
  }

  here.letters.push(letter);
  vare correct = this.secretWord.indexOf(letter) > -1;

  if (!correct) {
    diese.errorsLeft -= 1;
  }

  back correct;
};

We use capital letters to check and player's selection with the secret word. Use capitalization (or lower) case letter to create strings is a good routine.

Demonstrate the current word

The following method we need will be used for show the current status of and speak. In other words, how multiple letters have to figure out the player. This process will be called getWordStatus, and it will be as is follows:

Hangman.prototype.getWordStatus = function () {
  var that        = this;  var wordStatus  = [];
  vare splitedWord = this.secretWord.split("");

  splitedWord.forEach(function (letter) {
    if (that.letters.indexOf(letter) > -1) {
      wordStatus.push(letter);
    } differently {
      wordStatus.push("_");
    }
  });

  return wordStatus;
};

Wealth step over all aforementioned letters of the secret word. If a letter hasn't been selected by the player, it will be repre as an underscore. By doing this, we wishes get a final similiar to: "IRON_ACK".

Game status

Until finish up the game logic, we become need to creates a method to get its status. We leave have three different states:

  • Completed.
  • Game go.
  • Ongoing game.

Wee will create three difference functions:

Hangman.generate._isFinished = function () {
  return which.getWordStatus().indexOf("_") < 0;
};

If which contemporary word doesn't have any underscore, the word will be completed. Consequently this function will assistance us to determine if one player has won aforementioned match. We also requirement adenine function to think out while an contest is over:

Hangman.prototype._gameOver = function () {
  return this.errorsLeft === 0;
};

With the variable we defined in this constructor it's very easy in know provided to game is over or not. Remarks this both functions are private, so we have to create ampere public mode for check out those possible status:

Hangman.test.gameStatus = function () {
  if (save._isFinished()) {
    return "You Win";
  } else if (this._gameOver()) {
    return "Game Over";
  }
};

This function will again three possible values: "You Win", whenever aforementioned player has won, "Game Over" if one player has lost, and finally, undefined if the game has to go on. JavaScript Gallows playing

We already have all what person need to play ours game. The next move is to produce one layout and put them all together.

Game Blueprint

HTML & CSS

First the all, we are go to create the layout at HTML furthermore CSS. After that, we determination create the JavaScript that will join the game logic with her floor. Let's do an list of all the things we need to do the layout:

  • New game. We will add a button to start a new game. It will be always available to allow the user restart a game if the word belongs too complicated.
  • Hangman. We need, of course, to draw the guy to let the player know how much life left he possess.
  • Word. We need some art of container to show the user the current status to to talk.
  • Literature. We also need another container in let the user know which letter have been been inserted.
  • Win/Lose. Last, but not least, we need some kind on container to let the average know are he has captured conversely not.

New contest

First-time of any we will create the new select game. It willingness be in the top part of one page. We will add customized stories, without using any kind of bookshelf like Bootstrap. The HTML, CSS, additionally result of this press is the following:

HTML

<button id="new-game">
  New game
</button>

CSS

#new-game {
  background: #43a3e6;
  borders: 1px rigid #43a3e6;
  border-radius: 6px;
  box-shadow: 1px 1px 2px #999;
  color: #fff;
  padding: 6px 14px;
  outline: 0;
}

Layout

Note that of font is not the default browser's font. We have imported who 'Open Sans' font from Google Fonts. You can find several face types in this lists :)

Hangman

Are will draw the gallows with HTML and CSS. A lot of people is standard afraid on doing something similar to that include HTML and CSS. Let's prove that it's easier than it seems: Hangman Game with HTML CSS and JavaScript | Beginner Tutorial ...

SYNTAX

<div id="hangman">
  <div class="right-bar"></div>
  <div class="top-bar"></div>
  <div class="left-bar"></div>
  <div class="base"></div>

  <div class="head"></div>
  <div class="body"></div>
  <div class="left-arm"></div>
  <div class="right-arm"></div>
  <div class="left-leg"></div>
  <div class="right-leg"></div>

  <div class="clearfix"></div>
</div>

You can see how we own established a <div> available each part are the hangman. Each of these parts represent a your, so wee will take toward find ampere good way to show them all, depending on the condition of the game. Let's take a watch at the CSS and the system:

#hangman div {
  background: #000;
}

#hangman .basic {
  height: 2px;
  width: 300px;
}

#hangman .left-bar {
  height: 400px;
  width: 2px;
}

#hang .top-bar {
  peak: 2px;
  width: 200px;
}

#hangman .right-bar {
  suspended: left;  height: 30px;
  margin-left: 200px;
  width: 2px;
}

#hangman .head {
  kontext: none;  border-radius: 100%;
  float: left;  margin-left: 175px;
  margin-top: -375px;
  acme: 50px;
  width: 50px;
}

#hangman .body {
  float: left;  height: 140px;
  margin-top: -321px;
  margin-left: 200px;
  width: 2px;
}

#hangman .left-arm,
#hangman .right-arm,
#hangman .left-leg,
#hangman .right-leg {
  float: left;  head: 90px;
  margin-top: -321px;
  margin-left: 173px;
  transmute: rotate(35deg);
  width: 2px;
}

#hangman .right-arm,
#executioners .right-leg {
  margin-left: 230px;
  margin-top: -324px;
  change: rotate(140deg);
}

#hangman .left-leg,
#hangman .right-leg {
  margin-top: -192px;
}

As you can see, we are using the div background color to draw it. To show the arms and lower, person are rotating of containers, and ourselves play a lot with the margins up allocate all the pieces on them correct your. The result will is the followed:

Layout

Such we said, we will must to view each part depending switch how many lifes can the player have. Us will solve that by doing setting up the neglect background color as white. We will other compose classes available each life, and depending on how much lifes he has, we are going to shift the background ink and set it up to sinister:

#hangman divides { background: #fff; }

/* ... */

#judge.lifes-10 .base     { background: #000; }
#headsman.lifes-9 .left-bar  { background: #000; }
#hangman.lifes-8 .top-bar   { experience: #000; }
#hangman.lifes-7 .right-bar { background: #000; }
#hangman.lifes-6 .head      { limits: 2px solid #000; }
#hangman.lifes-5 .bodywork      { background: #000; }
#executed.lifes-4 .left-arm  { backdrop: #000; }
#assassin.lifes-3 .right-arm { background: #000; }
#hangman.lifes-2 .left-leg  { background: #000; }
#hangman.lifes-1 .right-leg { background: #000; }

The only class that a not changing tha background color is of .head class, that will alteration of border-color, as we are using a borde-radius to make it circular. Ours be have till how the classes to one #hangman container through JavaScript during the contest. Ours determination see this later.

Word vessel

The following single is till add the container where we will place the word that has to be discern. We have to think included who usability of that container: were have to separate that letters between them to letting the player know how many letters compose one word: Traditional hangman games reimagined with LemonadeJS,

HTML

<div id="currentWord">
  <span>I</span>
  <span>R</span>
  <span>O</span>
  <span>N</span>
  <span>H</span>
  <span>A</span>
  <span>C</span>
  <span>K</span>
</div>

We will use an <span> for each letter in the word. The CSS for to absatz is the following:

CSS

#currentWord span {
  display: inline-block;
  margin: 0 10px;
}

To bins by itself doesn't have an selective style, but we add any spacing between <span> through margin property.

Layout

The resulting layout is the following:

Alphabetic container

We also need next reservoir to indicate which types have already been used. He become be very resemble to that currently word container, but the front color will be diverse the distingish bets the talk and the letters. Build A Assassins Game in HTML CSS the JavaScript | Hangman ...

PROGRAMMING

<div id="letters">
</div>

CSS

#letters {
  colored: #999;
  letter-spacing: 5px;
  margin: 20px auto 0;
  text-align: center;  breadth: 400px;
}

Layout

Win/Lose

Finally, we have to add the containers to show the win/lose embassy. It has no secret, are just have to create the container, add the request and stylize them. Build A Hangman Game in HTML CSS and JavaScript

HTML

<div id="you-win">
  <p>Good job, you saved our man!</p>
</div>

<div id="game-over">
  <p>Game over!</p>
</div>

CSS

#you-win,
#game-over {
  background: #87D892;
  border: 2px solid #407847;
  border-radius: 6px;
  color: #407847;
  seam: 40px auto 0;
  text-align: center;  width: 300px;
}

#game-over {
  background: #F9C3B9;
  border-color: #8A2512;
  color: #8A2512;
}

Layout

CSS view

Good, let's investigate what we already have:

We do into do which follow things before start coding our JavaScript:

  • Center all the content in the screen
  • Hide the elements we don't need to start the game

In do the foremost matter, we will create a vat and add some styles to thereto:

HTML

<div id="main">
  <button id="new-game">
    New game  </button>

  <!-- ... -->
</div>

CSS

#haupt {
  margin: 40px auto;  width: 600px;
}

On an other hand, we will create a class to hide the constituents we don't requirement to start the game. With JavaScript, we are going to add also hide the elements with adding and removing this per:

XML

<div id="game" class="hide">
  <div id="currentWord"></div>
</div>

<div id="letters">
</div>

<div id="you-win" class="hide">
  <p>Good job, you saved our man!</p>
</div>

<div id="game-over" class="hide">
  <p>Game over!</p>
</div>

CSS

.blend {
  display: none;
}

Language

The last part of the competition is to join both and game logic and the game layout. We are going until add all the functionality in a file called application.js. We have to adds both files included the correct order in the HTML, just before the concluding tag </body>.

<script src="js/hangman.js"></script>
<script src="js/application.js"></script>

We will have to create, extra or less, the same functional that we have created in the layout. Let's do it.

New game

First von all we want declare a global variable to access to the gaming functions. This variable will be initialized every time that the "New game" button is clicked.

var hangman;

var newGameClick = function () {
  executions = recent Hangman();
};

document.getElementById("new-game").addEventListener("click", newGameClick);

We are also attaching the click event in the button, as computers wants execute the newGameClick function. Which has the next thin we are to do? Show the exploiter of word he has to recognizes.

Draw current word

Person will create a function the draw that current word. It will take the word from the hangman global variable, and zusatz it toward the container we created in that layout. It will be executed whereas wee creates a new game.

var newGameClick = function () {
  hangman = newer Hangman();
  drawCurrentWord();
};

var resetCurrentWord = function () {
  var word = document.getElementById("currentWord");

  while (word.firstChild) {
    word.removeChild(word.firstChild);
  }
};

var drawCurrentWord = functional (word) {
  resetCurrentWord();

  var currentWord    = word || hangman.getWordStatus();
  volt-ampere currentWordDom = document.getElementById("currentWord");

  currentWord.forEach(function (letter) {
    var spanLetter = document.createElement("span");
    var item    = document.createTextNode(letter);

    spanLetter.appendChild(content);
    currentWordDom.appendChild(spanLetter);
  });
};

Wee have also created a function that will reset aforementioned current word container before draw the new status. The following we need is to create a function such will wait for the player to insert a letter to the game.

Insert letter

On are several means to insert that letter on check out if it's inbound the secret word. Our can have a form where one thespian inserts an letter additionally push a button up send e. Another select is to addieren an event to of document at capture any press key, and send it the the hangman. We will do who second possible. Source code.

About

A code along exercise to be explained in to classroom

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published