Open In App

Build a Hangman Game using JavaScript

Last Updated : 19 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Hangman is a game where we have a hidden word, and we need to guess it by clicking on individual letters. When we click on a correct letter, it fills in a blank space. If we guess the word correctly, we win. But if we don’t guess it within a certain number of tries, we lose the game. Each wrong guess increases the hanging of a man on a rope. When the man is completely hung, the game ends.

Preview Image

oo

Build a Hangman Game using JavaScript

Approach

  • Create a project folder and save image, HTML, CSS, and JS files inside.
  • Write HTML for game layout, including buttons for alphabet characters and display areas.
  • Add CSS styles for visual appeal, including hover effects.
  • Implement game logic in JavaScript, managing character clicks, image display, and word guessing.
  • Ensure single character clicks per turn, track game progress, and display appropriate images and messages for wins and losses.

Example :The below code example implements the HTML, CSS and JavaScript to create an Build a Hangman Game using JavaScript with interactive operations.

HTML




<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, 
                                   initial-scale=1.0" />
    <title>Hangman Game</title>
    <link rel="stylesheet" href="/style.css" />
    <script src="/script.js" defer></script>
  </head>
  
  <body>
    <div class="game-modal" id="over">
      <div class="content">
        <h4>Game Over!</h4>
        <p>The correct word was: <b>rainbow</b></p>
        <button class="play-again">Play Again</button>
      </div>
    </div>
  
    <div class="container">
      <div class="hangman-box">
        <img
          src=
             "https://media.geeksforgeeks.org
              /wp-content/uploads/20240215173028/0.png"
          alt="hangman-img"
        />
        <h1>Hangman Game</h1>
        <div class="timer">Time left:
          <span id="timer-display">3:00</span>
        </div>
      </div>
      <div class="game-box">
        <ul class="word-display"></ul>
        <h4 class="hint-text">
          Hint:
          <b></b>
        </h4>
        <h4 class="guesses-text">
          Incorrect guesses:
          <b>0 / 6</b>
        </h4>
        <div class="keyboard"></div>
      </div>
    </div>
  </body>
</html>


CSS




* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "Times New Roman", Times, serif;
}
  
body {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  background: linear-gradient(45deg, #408e46, #556270);
  padding: 0 10px;
}
  
.container {
  width: 850px;
  background: #f8f9fa;
  display: flex;
  padding: 60px 40px;
  border-radius: 20px;
  align-items: flex-end;
  gap: 70px;
}
  
.timer {
  font-size: 1.3rem;
  text-align: center;
  margin-top: 20px;
  width: 60%;
  margin-left: 40px;
  padding: 12px 20px;
  background-color: #5a6175;
  border-radius: 20px;
  color: #ffffff;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.3);
}
  
#timer-display {
  font-weight: bold;
  color: #ff7e67;
}
  
.hangman-box img {
  max-width: 270px;
}
  
.hangman-box h1 {
  font-size: 1.45rem;
  margin-top: 20px;
  text-align: center;
  text-transform: uppercase;
}
  
.word-display {
  display: flex;
  gap: 10px;
  list-style: none;
  align-items: center;
  justify-content: center;
}
  
.word-display .letter {
  width: 28px;
  font-size: 2rem;
  font-weight: 600;
  text-transform: uppercase;
  text-align: center;
  margin-bottom: 40px;
  border-bottom: 3px solid #000;
}
  
.word-display .letter.guessed {
  border-color: transparent;
  margin: -40px 0 35px;
}
  
.game-box h4 {
  text-align: center;
  font-size: 1.1.rem;
  font-weight: 500;
  margin-bottom: 15px;
}
  
.game-box h4 b {
  font-weight: 600;
}
  
.game-box .guesses-text b {
  color: #ff0000;
}
  
.guesses-box .keyboard {
  display: flex;
  gap: 5px;
  margin-top: 40px;
  flex-wrap: wrap;
  justify-content: center;
}
  
.keyboard button[disabled] {
  opacity: 0.6;
  pointer-events: none;
}
  
:where(.game-modal, .keyboard) button {
  color: #ffffff;
  /* White text color */
  border-radius: 14px;
  cursor: pointer;
  outline: none;
  padding: 10px 20px;
  /* Increased padding for better visibility */
  border: none;
  margin: 1px;
  font-size: 1rem;
  font-weight: 600;
  background: #408e46;
  /* Light red background */
  text-transform: uppercase;
}
  
.keyboard button {
  padding: 10px 20px;
  /* Increased padding for better visibility */
  width: calc(100% / 9 - 5px);
}
  
.game-modal {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  padding: 0 10px;
  opacity: 0;
  pointer-events: none;
  z-index: 999;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  background: rgba(0, 0, 0, 0.6);
  transition: opacity 0.4s ease;
}
  
.game-modal.show {
  opacity: 1;
  pointer-events: auto;
  z-index: 999;
}
  
.game-modal .content {
  background: #b2d7b2;
  max-width: 420px;
  width: 50%;
  text-align: center;
  border-radius: 20px;
  padding: 30px;
}
  
.game-modal img {
  max-width: 200px;
  margin-bottom: 15px;
}
  
.game-modal h4 {
  font-size: 1.5rem;
}
  
.game-modal p {
  font-size: 1.15rem;
  margin: 10px 0 30px;
  font-weight: 500;
}
  
.game-modal p b {
  color: #e90e0e;
  /* Dark green color */
  font-size: 20px;
  font-weight: 600;
}
  
.game-modal button {
  padding: 12px 23px;
}
  
@media (max-width: 782px) {
  .container {
    flex-direction: column;
    padding: 30px 15px;
    align-items: center;
  }
  
  .hangman-box img {
    max-width: 200px;
  }
  
  .hangman-box h1 {
    display: none;
  }
}


Javascript




const wordDisplay = 
    document.querySelector(".word-display");
const keyboardDiv = 
    document.querySelector(".keyboard");
const hangmanImage = 
    document.querySelector(".hangman-box img");
const guessesText = 
    document.querySelector(".guesses-text b");
const gameModal = 
    document.querySelector(".game-modal");
const playAgainBtn = 
    document.querySelector(".play-again");
const timerDisplay = 
    document.querySelector(".timer");
  
const codingQuiz = [
  {
    word: "variable",
    hint: "A placeholder for a value.",
  },
  {
    word: "function",
    hint: "A block of code that performs a specific task.",
  },
  {
    word: "loop",
    hint: "A programming structure that repeats a 
    sequence of instructions until a specific condition is met.",
  },
  {
    word: "array",
    hint: "A data structure that 
    stores a collection of elements.",
  },
  {
    word: "boolean",
    hint: "A data type that can have
    one of two values, true or false.",
  },
  {
    word: "conditional",
    hint: "A statement that executes a block of
    code if a specified condition is true.",
  },
  {
    word: "parameter",
    hint: "A variable in a method definition.",
  },
  {
    word: "algorithm",
    hint: "A step-by-step procedure 
    or formula for solving a problem.",
  },
  {
    word: "debugging",
    hint: "The process of finding and 
    fixing errors in code.",
  },
  {
    word: "syntax",
    hint: "The rules that govern the structure of
    statements in a programming language.",
  },
];
  
let currentWord, correctLetters, wrongGuessCount, timerInterval;
const maxGuesses = 6;
const gameTimeLimit = 30;
  
const resetGame = () => {
  //Resetting all game variables and UI elements
  correctLetters = [];
  wrongGuessCount = 0;
  hangmanImage.src = 
  `https://media.geeksforgeeks.org
  /wp-content/uploads/20240215173028/0.png`;
  guessesText.innerText = `${wrongGuessCount} / ${maxGuesses}`;
  keyboardDiv
    .querySelectorAll("button")
    .forEach((btn) => (btn.disabled = false));
  wordDisplay.innerHTML = currentWord
    .split("")
    .map(() => `<li class="letter"></li>`)
    .join("");
  clearInterval(timerInterval);
  startTimer();
  gameModal.classList.remove("show");
};
  
const getRandomWord = () => {
  const { word, hint } =
    codingQuiz[Math.floor(Math.random() 
    * codingQuiz.length)];
  currentWord = word;
  console.log(word);
  document.querySelector(".hint-text b")
  .innerText = hint;
  resetGame();
};
  
const startTimer = () => {
  let timeLeft = gameTimeLimit;
  timerInterval = setInterval(() => {
    timeLeft--;
    timerDisplay.innerText = `Time left:
    ${Math.floor(timeLeft / 60)}:${
      timeLeft % 60 < 10 ? "0" : ""
    }${timeLeft % 60}`;
    if (timeLeft <= 0) {
      clearInterval(timerInterval);
      gameOver(false);
    }
  }, 1000);
};
const gameOver = (isVictory) => {
  setTimeout(() => {
    clearInterval(timerInterval);
    const modalText = isVictory
      ? ` Yeah! You found the word:`
      : `You Loss! The correct word was:`;
    gameModal.querySelector(
      "p"
    ).innerHTML = 
    `${modalText} <b>${currentWord}</b>`;
    gameModal.classList.add("show");
  }, 300);
};
const initGame = (button, clickedLetter) => {
  if (currentWord.includes(clickedLetter)) {
    [...currentWord].forEach((letter, index) => {
      if (letter === clickedLetter) {
        correctLetters.push(letter);
        wordDisplay.querySelectorAll("li")[index]
        .innerText = letter;
        wordDisplay.querySelectorAll("li")[index]
        .classList.add("guessed");
      }
    });
  } else {
    wrongGuessCount++;
    if (wrongGuessCount === 0) {
      hangmanImage.src = 
      `https://media.geeksforgeeks.org/wp-content
      /uploads/20240215173028/0.png`;
    }
    if (wrongGuessCount === 1) {
      hangmanImage.src = 
      `https://media.geeksforgeeks.org/wp-content
      /uploads/20240215173033/1.png`;
    }
    if (wrongGuessCount === 2) {
      hangmanImage.src = 
        
      `https://media.geeksforgeeks.org/wp-content
      /uploads/20240215173038/2.png`;
    }
    if (wrongGuessCount === 3) {
      hangmanImage.src = 
      `https://media.geeksforgeeks.org/wp-content
      /uploads/20240215172733/3.png`;
    }
    if (wrongGuessCount == 4) {
      hangmanImage.src = 
      `https://media.geeksforgeeks.org/wp-content
      /uploads/20240215173815/4.png`;
    }
    if (wrongGuessCount === 5) {
      hangmanImage.src = 
      `https://media.geeksforgeeks.org/wp-content
      /uploads/20240215173859/5.png`;
    }
    if (wrongGuessCount === 6) {
      hangmanImage.src =
      `https://media.geeksforgeeks.org/wp-content
      /uploads/20240215173931/6.png`;
    }
    // hangmanImage.src = 
    `images/hangman-${wrongGuessCount}.svg`;
  }
  
  button.disabled = true;
  guessesText.innerText = `${wrongGuessCount} / ${maxGuesses}`;
  
  if (wrongGuessCount === maxGuesses) 
  return gameOver(false);
  if (correctLetters.length === currentWord.length)
  return gameOver(true);
};
  
//Creating keyboard buttons 
//and adding event listerers
for (let i = 97; i <= 122; i++) {
  const button = document.createElement("button");
  button.innerText = String.fromCharCode(i);
  keyboardDiv.appendChild(button);
  button.addEventListener("click", (e) =>
    initGame(e.target, String.fromCharCode(i))
  );
}
getRandomWord();
playAgainBtn.addEventListener("click", getRandomWord);


Output:

2024-02-1517-56-20online-video-cuttercom1-ezgifcom-video-to-gif-converter

Build a Hangman Game using JavaScript



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads