Saturday, December 28, 2024
Google search engine
HomeLanguagesJavascriptWord Guessing Game using HTML CSS and JavaScript

Word Guessing Game using HTML CSS and JavaScript

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.

Javascript




// script.js
  
// Array of words to choose from
const words = [
    "java",
    "javascript",
    "python",
    "pascal",
    "ruby",
    "perl",
    "swift",
    "kotlin",
];
  
// Geting random word from the list
let randomIndex = Math.floor(Math.random() * words.length);
let selectedWord = words[randomIndex];
console.log(selectedWord);
  
// To store the already guessed letters
let guessedlist = [];
  
// For initial display Word
let displayWord = "";
for (let i = 0; i < selectedWord.length; i++) {
    displayWord += "_ ";
}
document.getElementById("displayWord").textContent = displayWord;
  
// Function to check Guessed letter
function guessLetter() {
    let inputElement = 
        document.getElementById("letter-input");
  
    // To check empty input
    if (!inputElement.value) {
        alert("Empty Input box. Please add input letter");
        return;
    }
  
    let letter = inputElement.value.toLowerCase();
  
    // Clear the input field
    inputElement.value = "";
  
    // Check if the letter has already been guessed
    if (guessedlist.includes(letter)) {
        alert("You have already guessed that letter!");
        return;
    }
  
    // Add the letter to the guessed letters array
    guessedlist.push(letter);
  
    // Update the word display based on the guessed letters
    let updatedDisplay = "";
    let allLettersGuessed = true;
    for (let i = 0; i < selectedWord.length; i++) {
        if (guessedlist.includes(selectedWord[i])) {
            updatedDisplay += selectedWord[i] + " ";
        } else {
            updatedDisplay += "_ ";
            allLettersGuessed = false;
        }
    }
    document.getElementById("displayWord")
        .textContent = updatedDisplay;
  
    // Check if all letters have been guessed
    if (allLettersGuessed) {
        alert("Congratulations! You guessed the word correctly!");
    }
}


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




/* style.css */
  
/* Styling for the heading */
h1 {
    background-color: rgb(231, 231, 231);
    color: green;
    font-size: xx-large;
    padding: 2%;
    /* width: 70vh; */
}
  
/* Style for the card and border  */
.card {
    min-width: 30%;
    width: 50vh;
    min-height: 30vh;
    box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
    transition: 0.3s;
    border-radius: 5px;
    margin: auto;
    padding: 2%;
}
  
/* Font and display style for complete body */
body {
    display: flex;
    text-align: center;
    font-family: "Gill Sans"
                   "Gill Sans MT"
                   Calibri, "Trebuchet MS",
                 sans-serif;
}
  
/* Adding style for input box */
input {
    width: 30px;
    padding: 1%;
    font-size: larger;
    text-align: center;
    margin-left: 2%;
}
  
/* Adding style for display word*/
#displayWord {
    font-size: xx-large;
}


Output:

Peek-2023-07-07-09-48

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments