JavaScript Word Guessing Game

The JavaScript Word Guessing game is a strong and brain-engaging activity that can help improve your memory.

In this game, you’re presented with random words on the dashboard. With the help of hints or questions, you try to figure out the right words.

This not only exercises your brain but also keeps you entertained. It’s like solving puzzles while enhancing your memory skills!

Also, learn –

JavaScript Color Picker Chrome Extension

JavaScript Password Strength Checker

In this game, a hint sentence will be provided at the beginning when you start playing, and you’ll also have the option to reset the hints if needed.

The difficulty of the hints might vary depending on the game’s level or length. Your goal is to correctly guess all the words based on these hints.

If you manage to guess all the words correctly, you’ll emerge as the winner of the game.

 

Steps to Create Word Guessing Game in JavaScript

Now follow the next all steps –

1. Create a Directory  Structure

First of all, Create the directory structure to create the word-guessing game

word-guessing/
     |__index.html
     |__style.css
     |__guessing-words.js
     |__script.js
     |

2. Create Word Guessing UI

This HTML code creates a responsive webpage for a word-guessing game with styling, game instructions, input fields, result displays, and reset functionality.

File Name – index.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>JavaScript Word Guessing - CodingStatus</title>

  <!-- Link to your custom CSS -->
  <link rel="stylesheet" href="style.css">

  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css">
</head>
<body>
  <div class="container">
    <div class="row">
      <div class="col-sm-6">
        <!-- Word Guessing Game -->
        <div class="game">
          <h1 class="text-success">Word Guessing Game</h1>
          <h3>Guess the Word!</h3>
          <p class="correct-result text-success"></p>
          <p class="help text-danger"></p>
          <div class="word-inputs">
            <!-- Word input elements can be added here -->
          </div>
          <input type="text" class="type-word">
          <div class="result">
            <p><b>Wrong Guess Letters</b></p>
            <p class="wrong-guess"></p>
            <p><b>Remaining chances</b></p>
            <p class="remaining-chance"></p>
          </div>
          <button class="btn btn-success reset-now">Reset Now</button>
        </div>
      </div>
      <div class="col-sm-6">
        <!-- Additional content for the second column can be added here -->
      </div>
    </div>
  </div>

  <!-- Include JavaScript files at the end of the body for faster page loading -->
  <script src="guessing-words.js"></script>
  <script src="script.js"></script>
</body>
</html>

Explanation:

  • <div class=”game“>: A section for the Word Guessing Game content.
  • <h1 class=”text-success“>Word Guessing Game</h1>: Displays a header with “Word Guessing Game” text in green.
  • <h3>Guess the Word!</h3>: Displays a subheader prompting users to guess the word.
  • <p class=”correct-result text-success“></p>: Creates a paragraph for displaying correct guess results in green.
  • <p class=”help text-danger“></p>: Creates a paragraph for displaying helpful hints or warnings in red.
  • <div class=”word-inputs“>: Placeholder for word input elements.
  • <input type=”text” class=”type-word“>: A text input field for users to enter guesses.
  • <div class=”result“>`: Section for displaying game results.
  • <p><b>Wrong Guess Letters</b></p: Displays a bold header for wrong guessed letters.
  • <p class=”wrong-guess“></p>: Paragraph for showing wrong guessed letters.
  • <p><b>Remaining chances</b></p>: Displays a bold header for remaining chances.
  • <p class=”remaining-chance“></p>: Paragraph for displaying remaining chances.
  • <button class=”btn btn-success reset-now“>Reset Now</button>: Creates a button styled with Bootstrap classes to reset the game.

3. Design Word Guessing UI

This code appears to be a snippet of Cascading Style Sheets (CSS) code that defines styles for an HTML element with the class name “game” and its child elements of the “input” type.

.game{
    border: 1px solid lightgray;
    padding: 20px;
    margin: 20px;
    text-align: center;
}

.game input{
    width: 20%;
    text-align: center;
    height: 55px;
    font-size: 25px;
    text-transform: uppercase;
    margin: 5px !important;
}

Explanation:

For elements with class “game”:

  • Add a light gray 1px solid border.
  • Apply 20px padding inside the element.
  • Set a 20px margin around the element.
  • Horizontally center-align the text content.

For “input” elements within elements of class “game”:

  • Make the input 20% wide within its container.
  • Horizontally center-align the text content within the input.
  • Set the input’s height to 55px.
  • Use a font size of 25px for the input text.
  • Convert input text to uppercase.
  • Apply a 5px margin around the input, with higher priority using “!important”.

4. Store Words & hints in an Object

This code defines an array called wordList that contains a collection of objects. Each object represents a word and its associated hint. The purpose of this code appears to be related to a word guessing or quiz-like game.

Here’s a summary of the code’s functionality:

The wordList array holds ten objects, each representing a word and a corresponding hint.
Each object has two properties:

  • word: A string representing the target word that the player needs to guess.
  • hint: A string providing a clue or description related to the target word.

File Name – gueesing-words.js

const wordList = [
    {
        word: "head",
        hint: "Invisible part of web page"
    },
    {
        word: "body",
        hint: "Visible Part of Web page"
    },
    {
        word: "html",
        hint: "HyperText Markup Language"
    },
    {
        word: "css",
        hint: "Styling Language"
    },
    {
        word: "angular",
        hint: "Single page Application language"
    },
    {
        word: "programmer",
        hint: "A person who writes Program"
    },
    {
        word: "coder",
        hint: "A person who codes"
    },
    {
        word: "coding",
        hint: "CodingStatus contains a programming word"
    },
    {
        word: "ecommerce",
        hint: "Shopping Website"
    },
    {
        word: "github",
        hint: "code hosting platform"
    }
]

5. Create a guessing Game Script

The code is for a word guessing game with improved variable organization and function definitions.

It handles selecting random words, user input, and game state. Event listeners manage game actions like resetting and starting.

File Name – script.js

let wordInputs = document.querySelector(".word-inputs");
let help = document.querySelector(".help");
let remainingChance = document.querySelector(".remaining-chance");
let wrongLetter = document.querySelector(".wrong-guess");
let resetNow = document.querySelector(".reset-now");
let typeWord = document.querySelector(".type-word");

let word = "";
let maxGuesses = 0;
let incorrectLetters = [];
let correctLetters = [];

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

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

const startGame = function(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;
                    wordInputs.querySelectorAll("input")[i].value = key;
                }
            }
        } else {
            maxGuesses--;
            incorrectLetters.push(` ${key}`);
        }
        remainingChance.innerText = maxGuesses;
        wrongLetter.innerText = incorrectLetters;
    }
    typeWord.value = "";

    setTimeout(() => {
        if (correctLetters.length === word.length) {
            help.innerText = `Congrats! You have guessed the right word`;
            // return randomWord();
        } else if (maxGuesses < 1) {
            help.innerText = `You have failed! You have 0 chances left to guess`;
            for (let i = 0; i < word.length; i++) {
                wordInputs.querySelectorAll("input")[i].value = word[i];
            }
        }
    }, 100);
};

randomWord();

resetNow.addEventListener("click", randomWord);
wordInputs.addEventListener("click", () => typeWord.focus());
document.addEventListener("keydown", () => typeWord.focus());
document.addEventListener("keyup", startGame);

Explanation

here is the pointwise explanation of the code in simple sentences:

  • The code sets up variables to store game elements and information.
  • Two main functions are defined: `randomWord()` and `startGame(e)`.
  • The `randomWord()` function picks a random word from a list, sets game settings, and displays a hint.
  •  It creates input fields for the word’s letters and initializes game variables
  • The `startGame(e)` function responds to user key presses during the game.
  • It checks if the pressed key is valid and not already guessed.
  • If the key matches a letter in the word, it updates the correct guesses.
  • If the key is incorrect, it decreases remaining guesses and updates wrong letters.
  • The game updates UI elements like remaining chances and wrong letters.
  • After each guess, it checks if the word is guessed or if no guesses remain.
  • If the word is guessed, it displays a congratulatory message.
  • If there are no remaining guesses, it reveals the word and indicates failure.
  • The game starts by selecting a random word and setting up the UI.
  • Event listeners are attached: Reset button to restart, input field click, and key events.

6. Play Word Guessing Game

To Play the Word Guessing Game, you need to follow the following points: –

open the game in your web browser. To start, hints will appear on the game dashboard. You can type the guessed word related to the hints or click the reset button to receive the next hints.

When you enter a correct guess, it will be displayed in the input box. If your guess is incorrect, it will appear in the wrong words section and reduce your remaining chances of guessing the word.

Once you correctly guess all the required words, you will win the game and receive congratulatory messages