9/2/2017 - 2:24 PM

Hangman Game Example

Hangman Game Example

<!-- Step 1: Create the Layout. -->
<!-- Step 2: Flag key sections with specific id names. These will be replaced by JavaScript -->
<!-- Step 2: Link to JavaScript (at end of the file) -->

<!DOCTYPE html>

<html lang='en-us'>


    <meta charset='UTF-8'>
    <title>Coding Bootcamp - Hangman</title>

    <!-- Bootstrap CDN -->
    <link rel='stylesheet' href='' integrity='sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7' crossorigin='anonymous'>

    /*css goes here  */



    <!-- Bootstrap Container will hold everything. -->
    <div class='container'>

      <!-- Jumbotron holds the title section. -->
      <div class='jumbotron'>
        <div class='container' style="margin: 20px; ">
          <h1>Coding Bootcamp - Hangman</h1>
          <h2>Guess the name of students from class!</h2>
          <small>Click any letter to begin...</small>

      <!-- Game counters held here. Panels are being used to hold various sections. -->
      <div class='row'>
        <div class='col-lg-12'>

          <!-- First Panel: Holds the Word to Guess (blanks and guessed word). -->
          <div class='panel panel-default'>
            <div class='panel-heading'>
              <h3 class='panel-title'><strong>Word to Guess</strong></h3>

            <div class='panel-body'>

              <!-- This h3 section called word-blanks is what we'll be replacing with letters as the user guesses. Pay particular attention to the id called ***word-blanks***. We'll be referencing this in the JavaScript. -->
              <h3 id='word-blanks'>_ _ _ _ _ _ _ _ _ </h3>



          <!-- Second Panel: Holds the list of Wrong User Guesses. -->
          <div class='panel panel-default'>
            <div class='panel-body'>

              <!-- This span section called wrong-guesses is where we will be dumping the wrong guesses. Pay particular attention to the id called ****wrong-guesses***. We'll be referencing this in the JavaScript. -->
              <strong>Wrong Guesses: </strong> <span id='wrong-guesses'></span>


          <!-- Third Panel: Holds the Number of Wrong Guesses. -->
          <div class='panel panel-default'>
            <div class='panel-body'>

              <!-- This span is where we'll dump the number of guesses left. Pay attention to the id called ****guesses-left**** we'll be referencing this in the JavaScript. -->
              <strong>Guesses Left: </strong> <span id='guesses-left'>9</span>



          <!-- Fourth Panel: Holds the number of Wins. -->
          <div class='panel panel-default'>

            <div class='panel-body'>

              <!-- This span called win-counter is where we'll be dumping the number of wins. Pay attention to the id called ****win-counter*** we'll be referencing this in the JavaScript. -->
              <strong>Wins: </strong> <span id='win-counter'>0</span>



          <!-- Fifth Panel: Holds the number of Losses. -->
          <div class='panel panel-default'>
            <div class='panel-body'>

              <!-- This span called loss-counter is where we'll be dumping the number of losses. Pay attention to the id called ****loss-counter***; we'll be referencing this in the JavaScript. -->
              <strong>Losses: </strong> <span id='loss-counter'>0</span>






    <!-- Adds a link to the JavaScript file. Loaded at the bottom so it waits for the HTML content to display first. If you put this at the top it will crash, because the HTML IDs won't exist yet.-->
    <script src='logic.js'></script>


// GLOBAL VARIABLES (Accessible by all functions)
// ==================================================================================================

// Array of Word Options (all lowercase).
var wordsList = ["jerome", "neena", "darion", "lou", "greg", "jordan",
  "jasmine", "stephen", "jacob", "adam", "rui", "luis"];

// Computer selected solution will be held here.
var chosenWord = "";

// This will break the solution into individual letters to be stored in array.
var lettersInChosenWord = [];

// This will be the number of blanks we show based on the solution.
var numBlanks = 0;

// Holds a mix of blank and solved letters (ex: 'n, _ _, n, _').
var blanksAndSuccesses = [];

// Holds all of the wrong guesses.
var wrongGuesses = [];

// Holds the letters guessed
var letterGuessed = "";

// Game counters
var winCounter = 0;
var lossCounter = 0;
var numGuesses = 9;

// FUNCTIONS (These are bits of code that we will call upon to run when needed).
// ==================================================================================================

// startGame()
// It's how we we will start and restart the game.
// (Note: It's not being run here. Function declarations like this are made for future use.)
function startGame() {

  // Reset the guesses back to 0.
  numGuesses = 9;

  // Solution chosen randomly from wordList.
  chosenWord = wordsList[Math.floor(Math.random() * wordsList.length)];

  // The word is broken into individual letters.
  lettersInChosenWord = chosenWord.split("");

  // We count the number of letters in the word.
  numBlanks = lettersInChosenWord.length;

  // We print the solution in console (for testing).

  // Here we *reset* the guess and success array at each round.
  blanksAndSuccesses = [];

  // Here we *reset* the wrong guesses from the previous round.
  wrongGuesses = [];

  // Fill up the blanksAndSuccesses list with appropriate number of blanks.
  // This is based on number of letters in solution.
  for (var i = 0; i < numBlanks; i++) {

  // Print the initial blanks in console.

  // Reprints the guessesLeft to 9.
  document.getElementById("guesses-left").innerHTML = numGuesses;

  // Prints the blanks at the beginning of each round in the HTML.
  document.getElementById("word-blanks").innerHTML = blanksAndSuccesses.join(" ");

  // Clears the wrong guesses from the previous round.
  document.getElementById("wrong-guesses").innerHTML = wrongGuesses.join(" ");

// checkLetters() function
// It's where we will do all of the comparisons for matches.
// Again, it's not being called here. It's just being made for future use.
function checkLetters(letter) {

  // This boolean will be toggled based on whether or not
  // a user letter is found anywhere in the word.
  var letterInWord = false;

  // Check if a letter exists inside the array at all.
  for (var i = 0; i < numBlanks; i++) {

    if (chosenWord[i] === letter) {

      // If the letter exists then toggle this boolean to true.
      // This will be used in the next step.
      letterInWord = true;

  // If the letter exists somewhere in the word,
  // then figure out exactly where (which indices).
  if (letterInWord) {

    // Loop through the word
    for (var j = 0; j < numBlanks; j++) {

      // Populate the blanksAndSuccesses with every instance of the letter.
      if (chosenWord[j] === letter) {

        // Here we set specific blank spaces to equal the correct letter
        // when there is a match.
        blanksAndSuccesses[j] = letter;

    // Log the current blanks and successes for testing.

  // If the letter doesn't exist at all...
  else {

    // Then we add the letter to the list of wrong letters.

    // We also subtract one of the guesses.



// roundComplete() function
// Here we will have all of the code that needs to be run after each guess is made.
function roundComplete() {

  // First, log an initial status update in the console
  // telling us how many wins, losses, and guesses are left.
  console.log("WinCount: " + winCounter + " | LossCount: " + lossCounter + " | NumGuesses: " + numGuesses);

  // ============

  // Update the HTML to reflect the new number of guesses.
  document.getElementById("guesses-left").innerHTML = numGuesses;

  // This will print the array of guesses and blanks onto the page.
  document.getElementById("word-blanks").innerHTML = blanksAndSuccesses.join(" ");

  // This will print the wrong guesses onto the page.
  document.getElementById("wrong-guesses").innerHTML = wrongGuesses.join(" ");

  // If our hangman string equals the solution.
  // (meaning that we guessed all the letters to match the solution)...
  if (lettersInChosenWord.toString() === blanksAndSuccesses.toString()) {

    // Add to the win counter

    // Give the user an alert
    alert("You win!");

    // Update the win counter in the HTML
    document.getElementById("win-counter").innerHTML = winCounter;

    // Restart the game

  // If we've run out of guesses
  else if (numGuesses === 0) {

    // Add to the loss counter

    // Give the user an alert
    alert("You lose");

    // Update the loss counter in the HTML
    document.getElementById("loss-counter").innerHTML = lossCounter;

    // Restart the game



// ==================================================================

// Starts the Game by running the startGame() function

// Then initiates the function for capturing key clicks.
document.onkeyup = function(event) {

  // Converts all key clicks to lowercase letters.
  letterGuessed = String.fromCharCode(event.keyCode).toLowerCase();

  // Runs the code to check for correct guesses.

  // Runs the code that ends each round.