HomeJavascriptWord Guessing Game Javascript

Word Guessing Game Javascript

Hey everyone. Welcome to today’s tutorial. In today’s tutorial, we will learn how to create a word guess game. Before we start learning how to create the word guessing game let us see how this game works.
 
Initially, we display a start screen. When the user clicks on the start button we display the game screen. The game includes a hint to the guess word, blanks to fill in by the user and a keyboard to enter the words.
 
The user is provided with 5 chances. If the user guesses 5 wrong letters he loses the game. And we display the answer to the game on the end screen.
If the user guesses the word they win.
 
If you are interested to learn javascript through more such projects you can check out the playlist here. This playlist consists of 100+ javascript projects with source code.

Video Tutorial:

Also if you would like to learn by watching a video tutorial you can check out the video down below. Subscribe to my youtube channel where I post new tips, tricks and tutorials every alternate day.

Project Folder Structure:

Before we start coding let us create the project folder structure. We create a project folder called – ‘Word Guessing Game’. Inside this folder, we have three files. These files are index.html, style.css and script.js.

HTML:

We begin with the HTML code. Copy the code below and paste it into your HTML document.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Word Guessing Game</title>
    <!--Google Fonts-->
    <link
      href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600&display=swap"
      rel="stylesheet"
    />
    <!-- Stylesheet -->
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div class="wrapper">
      <div class="hint-ref"></div>
      <div id="user-input-section"></div>
      <div id="message"></div>
      <div id="letter-container"></div>
    </div>
    <div class="controls-container">
      <div id="result"></div>
      <div id="word"></div>
      <button id="start">Start</button>
    </div>
    <!-- Script -->
    <script src="script.js"></script>
  </body>
</html>

CSS:

Next, we style our game using CSS. For this copy, the code provided to you below and paste it into your stylesheet.

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}
body {
  background-color: #7786f5;
}
.wrapper {
  position: absolute;
  width: 90%;
  max-width: 37em;
  background-color: #ffffff;
  padding: 7em 3em;
  position: absolute;
  transform: translate(-50%, -50%);
  top: 50%;
  left: 50%;
  text-align: center;
  border-radius: 1em;
}
.controls-container {
  background-color: #7786f5;
  position: absolute;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  top: 0;
}
#start {
  font-size: 1.2em;
  padding: 1em 3em;
  background-color: #ffffff;
  border: none;
  outline: none;
  border-radius: 2em;
  cursor: pointer;
}
#letter-container {
  display: flex;
  flex-wrap: wrap;
  gap: 0.8em 0.4em;
  justify-content: center;
  margin-top: 2em;
}
#letter-container button {
  background-color: #ffffff;
  border: 2px solid #7786f5;
  color: #7786f5;
  outline: none;
  border-radius: 0.3em;
  cursor: pointer;
  height: 3em;
  width: 3em;
}
#letter-container .correct {
  background-color: #008000;
  color: #ffffff;
  border: 2px solid #008000;
}
#letter-container .incorrect {
  background-color: #8a8686;
  color: #ffffff;
  border: 2px solid #8a8686;
}
.hint-ref {
  margin-bottom: 1em;
}
.hint-ref span {
  font-weight: 600;
}
#chanceCount {
  margin: 1em 0;
  position: absolute;
  top: 0.62em;
  right: 2em;
}
#word {
  font-weight: 600;
  margin: 1em 0 2em 0;
}
#word span {
  text-transform: uppercase;
  font-weight: 400;
}
.hide {
  display: none;
}

Javascript:

Finally, we add functionality to the game using Javascript. For this once again copy the code below and paste it into your script file. 

You can add as many words and hints as you like to the options array to make the game even more fun.

The steps included in creating this game are:

  • Create Initial References.
  • Generate random values from an array.
  • Create a Blocker function to disable all buttons
  • Create startGame(), stopGame()
  • Generate the word
  • Init()
  • Function on window load.

//Word and Hints Object const options = { aroma: "Pleasing smell", pepper: "Salt's partner", halt: "put a stop to", jump: "Rise suddenly ", shuffle: "Mix cards up ", combine: "Add; Mix", chaos: "Total disorder", labyrinth: "Maze", disturb: "Interrupt; upset ", shift: "Move; Period of word", machine: "Device or appliance", }; //Initial References const message = document.getElementById("message"); const hintRef = document.querySelector(".hint-ref"); const controls = document.querySelector(".controls-container"); const startBtn = document.getElementById("start"); const letterContainer = document.getElementById("letter-container"); const userInpSection = document.getElementById("user-input-section"); const resultText = document.getElementById("result"); const word = document.getElementById("word"); const words = Object.keys(options); let randomWord = "", randomHint = ""; let winCount = 0, lossCount = 0; //Generate random value const generateRandomValue = (array) => Math.floor(Math.random() * array.length); //Block all the buttons const blocker = () => { let lettersButtons = document.querySelectorAll(".letters"); stopGame(); }; //Start Game startBtn.addEventListener("click", () => { controls.classList.add("hide"); init(); }); //Stop Game const stopGame = () => { controls.classList.remove("hide"); }; //Generate Word Function const generateWord = () => { letterContainer.classList.remove("hide"); userInpSection.innerText = ""; randomWord = words[generateRandomValue(words)]; randomHint = options[randomWord]; hintRef.innerHTML = `<div id="wordHint"> <span>Hint: </span>${randomHint}</div>`; let displayItem = ""; randomWord.split("").forEach((value) => { displayItem += '<span class="inputSpace">_ </span>'; }); //Display each element as span userInpSection.innerHTML = displayItem; userInpSection.innerHTML += `<div id='chanceCount'>Chances Left: ${lossCount}</div>`; }; //Initial Function const init = () => { winCount = 0; lossCount = 5; randomWord = ""; word.innerText = ""; randomHint = ""; message.innerText = ""; userInpSection.innerHTML = ""; letterContainer.classList.add("hide"); letterContainer.innerHTML = ""; generateWord(); //For creating letter buttons for (let i = 65; i < 91; i++) { let button = document.createElement("button"); button.classList.add("letters"); //Number to ASCII[A-Z] button.innerText = String.fromCharCode(i); //Character button onclick button.addEventListener("click", () => { message.innerText = `Correct Letter`; message.style.color = "#008000"; let charArray = randomWord.toUpperCase().split(""); let inputSpace = document.getElementsByClassName("inputSpace"); //If array contains clicked value replace the matched Dash with Letter if (charArray.includes(button.innerText)) { charArray.forEach((char, index) => { //If character in array is same as clicked button if (char === button.innerText) { button.classList.add("correct"); //Replace dash with letter inputSpace[index].innerText = char; //increment counter winCount += 1; //If winCount equals word length if (winCount == charArray.length) { resultText.innerHTML = "You Won"; startBtn.innerText = "Restart"; //block all buttons blocker(); } } }); } else { //lose count button.classList.add("incorrect"); lossCount -= 1; document.getElementById( "chanceCount" ).innerText = `Chances Left: ${lossCount}`; message.innerText = `Incorrect Letter`; message.style.color = "#ff0000"; if (lossCount == 0) { word.innerHTML = `The word was: <span>${randomWord}</span>`; resultText.innerHTML = "Game Over"; blocker(); } } //Disable clicked buttons button.disabled = true; }); //Append generated buttons to the letters container letterContainer.appendChild(button); } }; window.onload = () => { init(); };

That’s all for this tutorial. If you face any issues while creating this code you can download the source code by clicking on the ‘Download Code’ button below. Also, If you have any queries, suggestions or feedback you can comment below.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

four × five =

Most Popular