Word Guessing Game Using JavaScript
Published: 2023-06-08 06:13:08

Hey friends, today in this blog, you’ll learn to build a Word Guessing Game in HTML, CSS, and JavaScript. This game is similar to the hangman game.

To create this **[Word Guessing Game](https://www.codewithrandom.com/2023/05/07/word-guessing-game-in-javascript/)** in JavaScript. First, you need to create four Files: HTML, CSS & JavaScript Files. After creating these files just paste the given codes into your file. You can also download the source code files of this Word Guessing Game from the below GitHub button.

First, create an HTML file with the name index.html and paste the given codes into your HTML file. Remember, you’ve to create a file with a .html extension.

## HTML Code For Word Guessing Game:-
```
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8" />
    <title>Guess a Word Game JavaScript</title>
    <link rel="stylesheet" href="style.css" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  </head>
  <body>
    <div class="wrapper">
      <h1>Guess the Word</h1>
      <div class="content">
        <input type="text" class="typing-input" maxlength="1" />
        <div class="inputs"></div>
        <div class="details">
          <p class="hint">Hint: <span></span></p>
          <p class="guess-left">Remaining guesses: <span></span></p>
          <p class="wrong-letter">Wrong letters: <span></span></p>
        </div>
        <button class="reset-btn">Reset Game</button>
      </div>
    </div>

    <script src="js/words.js"></script>
    <script src="js/script.js"></script>
  </body>
</html>
```
The code is a web page with an HTML document. The code has a head, which includes meta tags and links to style sheets. There is also a title tag that contains the text "Guess a Word Game JavaScript".

The body of the code contains two divs: one for the game board and one for the word list. The code is the head of a web page. The code contains meta tags that define the language, character set, and title of the webpage. The code also contains a link to style.css which defines styles for the webpage.

The code is a web page with two divs. The first is the wrapper, which contains the h1 and has an input field for typing in words. The second is content, which has an input field as well but also includes a button to reset the game.

The script tag at the top of this code loads up some JavaScript files that are needed by this page: "js/words.js" and "js/script.js". The code is a game that asks the user to guess a word.

The code includes an input field, which will be used for the user to type in their guess. A div with class "content" contains the words that are being guessed and a div with class "inputs" displays all of the letters that have been typed into the input field so far.

Second step to  create  A Word Guessing Game in HTML CSS & JavaScript is create a CSS file with the name style.css and paste the given codes into your CSS file. Remember, you’ve to create a file with a .css extension.

## CSS Code For Word Guessing Game:-
```
/* Import Google font - Poppins */
@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600&display=swap");
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}
body {
  display: flex;
  padding: 0 10px;
  min-height: 100vh;
  align-items: center;
  justify-content: center;
  background: #e2dcc8;
}
.wrapper {
  width: 430px;
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
}
.wrapper h1 {
  font-size: 25px;
  font-weight: 500;
  padding: 20px 25px;
  border-bottom: 1px solid #ccc;
}
.wrapper .content {
  margin: 25px 25px 35px;
}
.content .inputs {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}
.inputs input {
  height: 57px;
  width: 56px;
  margin: 4px;
  font-size: 24px;
  font-weight: 500;
  color: #e2dcc8;
  text-align: center;
  border-radius: 5px;
  background: none;
  pointer-events: none;
  text-transform: uppercase;
  border: 1px solid #b5b5b5;
}
.typing-input {
  opacity: 0;
  z-index: -999;
  position: absolute;
  pointer-events: none;
}
.inputs input:first-child {
  margin-left: 0px;
}
.content .details {
  margin: 20px 0 25px;
}
.details p {
  font-size: 19px;
  margin-bottom: 10px;
}
.content .reset-btn {
  width: 100%;
  border: none;
  cursor: pointer;
  color: #fff;
  outline: none;
  padding: 15px 0;
  font-size: 17px;
  border-radius: 5px;
  background: #e2dcc8;
  transition: all 0.3s ease;
}
.content .reset-btn:hover {
  background: #e2dcc8;
}

@media screen and (max-width: 460px) {
  .wrapper {
    width: 100%;
  }
  .wrapper h1 {
    font-size: 22px;
    padding: 16px 20px;
  }
  .wrapper .content {
    margin: 25px 20px 35px;
  }
  .inputs input {
    height: 51px;
    width: 50px;
    margin: 3px;
    font-size: 22px;
  }
  .details p {
    font-size: 17px;
  }
  .content .reset-btn {
    padding: 14px 0;
    font-size: 16px;
  }
}
```
The code is a wrapper for an h1 element. The wrapper has a width of 430px and is positioned at the bottom left corner of the screen. The background color is #fff, which creates a white background with rounded corners. The border-radius property sets 10px rounded corners on all four sides of the container.

A box shadow is applied to give it depth and make it look like there's something behind it. The code will create a wrapper with a width of 430px and background color of #fff.

The wrapper will have 10px rounded corners and the box-shadow will be 0 10px 25px rgba(0, 0, 0, 0.1). The content inside the wrapper will have a margin of 25px on each side.

Then The code starts with a div that has the class of "inputs". Inside this div, there are two input fields. The first input field is for typing in text and the second input field is for selecting an option from a drop-down menu. The code starts by setting up some basic styles to make sure everything looks nice and neat.

It sets the width of each input field to 56px, which makes them wide enough so that users can type without having to scroll horizontally across their screens.

It also sets the height of each input field to 57px, which means they're tall enough so that users don't have to scroll vertically down their screens when they're filling out forms or typing in text boxes.

Next it adds some margins around each form element so that it doesn't look too crowded on smaller devices like phones or tablets where space might be limited due to screen size constraints.

Finally, it adds a border radius around each form element because borders are cool and people love borders! The code is used to create a simple input field.

Third step to  create  A Word Guessing Game in HTML CSS & JavaScript is create a JavaScript file with the name script.js and paste the given codes into your JavaScript file. Remember, you’ve to create a file with a .js extension and it should be inside the js folder.

## Word Guessing Game Javascript Code:-

**1. script.js File**
```
const inputs = document.querySelector(".inputs"),
hintTag = document.querySelector(".hint span"),
guessLeft = document.querySelector(".guess-left span"),
wrongLetter = document.querySelector(".wrong-letter span"),
resetBtn = document.querySelector(".reset-btn"),
typingInput = document.querySelector(".typing-input");

let word, maxGuesses, incorrectLetters = [], correctLetters = [];

function randomWord() {
    let ranItem = wordList[Math.floor(Math.random() * wordList.length)];
    word = ranItem.word;
    maxGuesses = word.length >= 5 ? 8 : 6;
    correctLetters = []; incorrectLetters = [];
    hintTag.innerText = ranItem.hint;
    guessLeft.innerText = maxGuesses;
    wrongLetter.innerText = incorrectLetters;

    let html = "";
    for (let i = 0; i < word.length; i++) {
        html += `<input type="text" disabled>`;
        inputs.innerHTML = html;
    }
}
randomWord();

function initGame(e) {
    let key = e.target.value.toLowerCase();
    if(key.match(/^[A-Za-z]+$/) && !incorrectLetters.includes(` ${key}`) && !correctLetters.includes(key)) {
        if(word.includes(key)) {
            for (let i = 0; i < word.length; i++) {
                if(word[i] == key) {
                    correctLetters += key;
                    inputs.querySelectorAll("input")[i].value = key;
                }
            }
        } else {
            maxGuesses--;
            incorrectLetters.push(` ${key}`);
        }
        guessLeft.innerText = maxGuesses;
        wrongLetter.innerText = incorrectLetters;
    }
    typingInput.value = "";

    setTimeout(() => {
        if(correctLetters.length === word.length) {
            alert(`Congrats! You found the word ${word.toUpperCase()}`);
            return randomWord();
        } else if(maxGuesses < 1) {
            alert("Game over! You don't have remaining guesses");
            for(let i = 0; i < word.length; i++) {
                inputs.querySelectorAll("input")[i].value = word[i];
            }
        }
    }, 100);
}

resetBtn.addEventListener("click", randomWord);
typingInput.addEventListener("input", initGame);
inputs.addEventListener("click", () => typingInput.focus());
document.addEventListener("keydown", () => typingInput.focus());
```
The code is a function that randomly generates a word from the list of words.
 It then creates an input field with text disabled, and it loops through each letter in the word to create an input field for each letter.
 The code is quite simple and easy to understand.
 The code first creates an array of words, then it randomly selects a word from the list.
 The code then creates a text input field with the disabled attribute so that users cannot submit their guesses until they have entered all six letters of the word.
The code starts by checking if the input is a letter.
 If it is, then the code checks to see if that letter is in the word list.
 If it's not, then the code increments maxGuesses and adds that letter to incorrectLetters .
 The code also sets up an alert box with "Congrats!
 You found the word" followed by whatever word was chosen at random.
 If correctLetters has more letters than words in our list, then we check for whether or not there are any remaining guesses left.
 If there are no remaining guesses left, then we set all of our inputs' values to be equal to their corresponding words in our list (word[i] ).
 The code is meant to be executed when the user presses a key on the keyboard.
 The code first checks if the inputted key is in the correct set of letters.
 If it's not, then it will check for an input with that same letter in its name and replace its value with that letter.
 If there are no more guesses left, then it will show an alert saying "Game over!"
 and reset all inputs to their original values.

Last step to  create  A Word Guessing Game in HTML CSS & JavaScript is create a JavaScript file with the name words.js and paste the given codes into your JavaScript file. Remember, you’ve to create a file with a .js extension and it should be inside the js folder. We’ll store random word details as an object in this file.

**2. words.js**
```
let wordList = [
    {
        word: "python",
        hint: "programming language"
    },
    {
        word: "guitar",
        hint: "a musical instrument"
    },
    {
        word: "aim",
        hint: "a purpose or intention"
    },
    {
        word: "venus",
        hint: "planet of our solar system"
    },
    {
        word: "gold",
        hint: "a yellow precious metal"
    },
    {
        word: "ebay",
        hint: "online shopping site"
    },
    {
        word: "golang",
        hint: "programming language"
    },
    {
        word: "coding",
        hint: "related to programming"
    },
    {
        word: "matrix",
        hint: "science fiction movie"
    },
    {
        word: "bugs",
        hint: "related to programming"
    },
    {
        word: "avatar",
        hint: "epic science fiction film"
    },
    {
        word: "gif",
        hint: "a file format for image"
    },
    {
        word: "mental",
        hint: "related to the mind"
    },
    {
        word: "map",
        hint: "diagram represent of an area"
    },
    {
        word: "island",
        hint: "land surrounded by water"
    },
    {
        word: "hockey",
        hint: "a famous outdoor game"
    },
    {
        word: "chess",
        hint: "related to a indoor game"
    },
    {
        word: "viber",
        hint: "a social media app"
    },
    {
        word: "github",
        hint: "code hosting platform"
    },
    {
        word: "png",
        hint: "a image file format"
    },
    {
        word: "silver",
        hint: "precious greyish-white metal"
    },
    {
        word: "mobile",
        hint: "an electronic device"
    },
    {
        word: "gpu",
        hint: "computer component"
    },
    {
        word: "java",
        hint: "programming language"
    },
    {
        word: "google",
        hint: "famous search engine"
    },
    {
        word: "venice",
        hint: "famous city of waters"
    },
    {
        word: "excel",
        hint: "microsoft product for windows"
    },
    {
        word: "mysql",
        hint: "a relational database system"
    },
    {
        word: "nepal",
        hint: "developing country name"
    },
    {
        word: "flute",
        hint: "a musical instrument"
    },
    {
        word: "crypto",
        hint: "related to cryptocurrency"
    },
    {
        word: "tesla",
        hint: "unit of magnetic flux density"
    },
    {
        word: "mars",
        hint: "planet of our solar system"
    },
    {
        word: "proxy",
        hint: "related to server application"
    },
    {
        word: "email",
        hint: "related to exchanging message"
    },
    {
        word: "html",
        hint: "markup language for the web"
    },
    {
        word: "air",
        hint: "related to a gas"
    },
    {
        word: "idea",
        hint: "a thought or suggestion"
    },
    {
        word: "server",
        hint: "related to computer or system"
    },
    {
        word: "svg",
        hint: "a vector image format"
    },
    {
        word: "jpeg",
        hint: "a image file format"
    },
    {
        word: "search",
        hint: "act to find something"
    },
    {
        word: "key",
        hint: "small piece of metal"
    },
    {
        word: "egypt",
        hint: "a country name"
    },
    {
        word: "joker",
        hint: "psychological thriller film"
    },
    {
        word: "dubai",
        hint: "developed country name"
    },
    {
        word: "photo",
        hint: "representation of person or scene"
    },
    {
        word: "nile",
        hint: "largest river in the world"
    },
    {
        word: "rain",
        hint: "related to a water"
    },
]
```
A **[Word Guessing Game](https://www.codewithrandom.com/2023/05/07/word-guessing-game-in-javascript/)** in  JavaScript is now complete. We implemented this with just plain old JavaScript and used the concept of Object-Oriented-Programming. I hope you enjoyed this and as always you can find the code on my GitHub.

If you enjoyed reading this post and have found it useful for you, then please give share it with your friends, and follow me to get updates on my upcoming posts. You can connect with me on Instagram.

if you have any confusion Comment below or you can contact us by filling out our contact us form from the home section. 

written by – Ninja_webTech