Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
Build a Memory Card Game Using HTML CSS and JavaScript
Next article icon

Word Guessing Game using HTML CSS and JavaScript

Last Updated : 30 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

  • HTML
  • CSS
  • JavaScript

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

Output:

Peek-2023-07-07-09-48

Next Article
Build a Memory Card Game Using HTML CSS and JavaScript
https://media.geeksforgeeks.org/auth/avatar.png
Anonymous
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • JavaScript-Projects

Similar Reads

  • Create a snake game using HTML, CSS and JavaScript
    Snake Game is a single-player game where the snake gets bigger by eating the food and tries to save itself from the boundary of the rectangle and if the snake eats their own body the game will be over. Game Rules:If the snake goes out of the boundary or eats its own body the game will be over.Prereq
    4 min read
  • Design Dragon's World Game using HTML CSS and JavaScript
    Project Introduction: "Dragon's World" is a game in which one dragon tries to save itself from the other dragon by jumping over the dragon which comes in its way. The score is updated when one dragon saves himself from the other dragon. The project will contain HTML, CSS and JavaScript files. The HT
    6 min read
  • 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
    4 min read
  • Build a Memory Card Game Using HTML CSS and JavaScript
    A memory game is a type of game that can be used to test or check the memory of a human being. It is a very famous game. In this game, the player has some cards in front of him and all of them facing down initially. The player has to choose a pair of cards at one time and check whether the faces of
    6 min read
  • Create a Simon Game using HTML CSS & JavaScript
    In this article, we will see how to create a Simon Game using HTML, CSS, and JavaScript. In a Simon game, if the player succeeds, the series becomes progressively longer and more complex. Once the user is unable to repeat the designated order of the series at any point, the game is over. Prerequisit
    5 min read
  • Create a Minesweeper Game using HTML CSS & JavaScript
    Minesweeper is a classic puzzle game that challenges your logical thinking and deduction skills. It's a great project for developers looking to improve their front-end web development skills. In this article, we'll walk through the steps to create a Minesweeper game using HTML, CSS, and JavaScript.
    4 min read
  • Whack-a-Mole Game using HTML CSS and JavaScript
    Whack-A-Mole is a classic arcade-style game that combines speed and precision. The game is set in a grid of holes, and the objective is to "whack" or hit the moles that randomly pop up from these holes. In this article, we are going to create Whack-a-Mole using HTML, CSS and JavaScript. Preview Imag
    3 min read
  • Simple HTML CSS and JavaScript Game
    Tap-the-Geek is a simple game, in which the player has to tap the moving GeeksForGeeks logo as many times as possible to increase their score. It has three levels easy, medium, and hard. The speed of the circle will be increased from level easy to hard. I bet, it is very difficult for the players to
    4 min read
  • Design Hit the Mouse Game using HTML, CSS and Vanilla Javascript
    In this article, we are going to create a game in which a mouse comes out from the holes, and we hit the mouse with a hammer to gain points. It is designed using HTML, CSS & Vanilla JavaScript. HTML Code: First, we create an HTML file (index.html).Now, after creating the HTML file, we are going
    5 min read
  • Create a 2D Brick Breaker Game using HTML CSS and JavaScript
    In this article, we will see how to create a 2D Brick Breaker Game using HTML CSS & JavaScript. Most of you already played this game on your Mobile Phones where you control a paddle to bounce a ball, aiming to demolish a wall of bricks arranged at the top of the screen. 2D Brick Breaker Game is
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences