Open In App

Word Guessing Game using HTML CSS and JavaScript

Last Updated : 30 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

In this article, we will see how can we implement a word-guessing game with the help of HTML, CSS, and JavaScript. 

Here, we have provided a hint key & corresponding total number of gaps/spaces depending upon the length of the word and accept only a single letter as an input for each time. If it is correct, then that letter will fill in that specific blank space, otherwise, the guessing will be continued, accordingly. It will look like the below image:

Prerequisites:

Approach:

  • Create the Game structure using Html tags,  like <div>, <h1> for the heading, <p> to display the word and the hint, and HTML input tag for guessed input letters with corresponding classes and IDs.
  • Add the different styling properties to the game using classes and elements that will define the padding, margin, font sizes to text, alignments, colors, etc to the specific elements.
  • In JavaScript, first, create an array of words to choose from for the quiz.
  • Then select a random word to display from the list by selecting a random index using JavaScript Math.random() method.
  • Initially display all the letters as “_ ” or dash by taking a new variable named displayWord of the same length as the selected word.
  • Push the guessed input in the guessedList array using array.push() and update the letter in displayWord at its every occurrence using a loop.
  • Every time check if the letter is already guessed show an alert “You have already guessed that letter”.
  • Display “You have guessed the word correctly” on alert when all letters have been guessed.

Project Structure:

Screenshot-from-2023-07-06-12-39-41

Project Structure

Example: This example describes the basic implementation of the word guessing game using HTML, CSS, and Javascript.

HTML
<!-- index.html -->

<!DOCTYPE html>
<html>

<head>
    <title>Word Guessing Game</title>
    <link rel="stylesheet" 
          href="style.css" />
       <script src="./script.js"></script>
</head>

<body>
    <div class="card">
        <h1>Guess the word</h1>
        <p>
              <b>Hint:</b> A programming language
          </p>
        <p id="displayWord"></p>
        <p>Guess one letter:

            <input type="text" 
                   maxlength="1" 
                   id="letter-input">
        </p>
        <button onclick="guessLetter()">
              Submit
          </button>
    </div>
</body>

</html>
CSS JavaScript

Output:

Peek-2023-07-07-09-48

Next Article

Similar Reads

three90RightbarBannerImg