Search
Close this search box.
Search
Close this search box.

Creating a Responsive Word Guessing Game Using JavaScript

Word Guessing Game

Table of Contents

Hi my pals! We’re going to learn how to make an HTML, CSS, and JavaScript word guessing game today in this blog. The Hangman game and this one are comparable.

How do I continue playing the word guessing game in JavaScript?

You must first generate the HTML, CSS, and JavaScript files in order to construct this word guessing game in JavaScript. You just need to put the provided code into your files after making these ones.

To begin, make an HTML file called Index.html, then paste the provided code into it. Recall that a file with the.html extension must be created.

Now let's review the coding section.

HTML Code -

				
					<!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>
				
			

Explanation of HTML Code -

  • HTML code explanation: The code is an HTML webpage document. The head of the code contains links to style sheets and meta tags. Additionally, there is a title tag with the sentence “Guess the word game using JavaScript.”
  • The two primary sections of the code are one for the word list and one for the game board. A webpage’s code is its core content. The language, character set, and webpage title are defined via meta tags in the code. A link to style.css, which specifies the webpage’s styling, is also present in the code.
  • The user can type their guess in the input space provided in the code. The words being guesses have been placed in the div with class “content,” and all of the letters entered so far in the input box are shown in the div with class “input.”

HTML Code Output -

HTML Output

Making a style.css file and pasting the provided code into it is the second stage in making a word guessing game with HTML, CSS, and JavaScript. Recall that a file with the.css extension must be created.

CSS Code -

				
					/* 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;
  }
}
				
			

Explanation of CSS code -

  • The h1 element is wrapped in the code. The wrapper is positioned in the lower left corner of the screen and has a width of 430 pixels. With rounded corners and a white background, the background color is #fff. The container’s all-around rounded corners are set by the border-radius parameter.
  • A box shadow is used to give it depth and indicate that there is something behind it. The wrapper will produce a box with a #fff background color and a width of 430 pixels.
  • The wrapper has box-shadow set to 0 10px 25px rgba(0, 0, 0, 0.1) and rounded corners of 10px. The content within the wrapper will have a 25px margin on both sides.
  • The code then begins with a div that has the class “input” on it. This division has two input fields inside of it. You enter text in the first input area and choose an item from a dropdown menu in the second. The code begins by defining a few basic styles to make sure everything appears nice and tidy.
  • It makes each input field big enough for users to text without having to scroll horizontally across their screens by setting its width to 56 pixels.
  • Additionally, it sets each input field’s height to 57 pixels, making them rather big to prevent users from having to scroll down their screens excessively when completing forms or entering data in text boxes.
  • Next, it creates a space around every form element to avoid crowding on smaller screens, such as those found on phones or tablets, where available space may be restricted.
  • Lastly, because borders are attractive and appealing to people, it adds a border radius to each form element! A basic input field is created using the code.

Making a JavaScript file called script.js and pasting the provided code into it is the third step in making a word guessing game using HTML, CSS, and JavaScript. Recall that the file you produce must have the.js extension and be located inside the js folder.

CSS code Output -

CSS Output

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());
				
			
  • A function in the code creates a word at random from a list of words.
  • Next, it turns off the text to generate an input field, iterating through the word’s letters to generate a field for every character.
  • The code is really straightforward and simple to understand.
  • The code generates a list of words first, then chooses a word at random from it.
  • The user can’t submit their guess until they’ve entered all six letters of the word.
  • so the code first disables a special function and creates a text input form.
  • The first thing the code does is see if the input is a letter.
  • The first thing the code does is see if the input is a letter.
  • If so, the code determines whether that letter is present in the word list.
  • If not, the code adds that letter to the incorrect guesses and raises maxGuesses.
  • Additionally, the code creates a “Congratulations!” notice box.
  • After it chooses a word at random, you are given the word.
  • We look to see if there are any additional guesses if the word has more letters than the right answers.
  • The code resets all of our inputs to their initial values (word[i]) if there are no more guesses.
  • The code runs when a key is pressed on the keyboard by the use.
  • The code first verifies that the key pressed is in the proper character set.
  • If not, it will alter its value to that character and verify if the input has the same character in its name.
  • When there are no more guesses, an alert stating “Game Over!” will appear.
  • and return the initial values of each input to them.

 

Making a JavaScript file named Words.js and pasting the provided code into it is the last step in creating a word-guessing game using HTML, CSS, and JavaScript. Recall that a file with the.js extension must be created and placed inside the js folder.

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"
    },
]
				
			

This concludes the JavaScript word guessing game. We have implemented it using only JavaScript and the idea of object-oriented programming. As always, you can access the code on my codepen page. I hope you enjoyed it.

Final Output -

See the Pen Untitled by Snake (@Snakeeys-) on CodePen.

Code by: Snake

Project Link – Codepen

Written by: cssiseasy

Please tell your friends about this post and follow me to receive updates on my future blogs if you liked it and found it helpful. I may be reached on Instagram.

Please use the contact form on the home page or leave a comment below if you have any questions.

Facebook
Twitter
LinkedIn
Telegram
Email
WhatsApp

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top