Hey Friends, Let's Build a Word Guessing Game Together!
Hey everyone! Today, we're going to create an awesome Word Guessing Game using HTML, CSS, and JavaScript. This project is a great way to understand how front-end web development works and have fun while coding.
Why Build a Word Guessing Game?
- Enhances JavaScript Skills: Working with loops, conditionals, and event listeners improves coding proficiency.
- Interactive User Experience: Engaging features like hints, animations, and scoring enhance user involvement.
- Practice HTML & CSS Styling: Strengthens UI/UX skills with better structuring and aesthetics.
Technologies Used
HTML: Provides the structural layout of the game.
CSS: Styles the game and adds animations.
JavaScript: Implements the game logic.
Step 1: Setting Up the HTML Structure
First, let's create the structure of our game using HTML. This will include a heading, a word display area, an input field for guessing letters, and buttons to interact with the game.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Word Guessing Game</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<h1>Word Guessing Game - HTML Code Example</h1>
<p>Guess the hidden word! You have <span id="attempts">6</span> attempts left.</p>
<div id="word-display"></div>
<input type="text" id="guess-input" maxlength="1" placeholder="Enter a letter">
<button id="guess-btn">Guess</button>
<button id="hint-btn">Hint</button>
<button id="reset-btn">Reset</button>
<p id="message"></p>
<p>Score: <span id="score">0</span></p>
</div>
<script src="script.js"></script>
</body>
</html>
This HTML file provides the user interface. Now, let's add some style to make it look nice.
Key Features of the Game
- Random Word Selection: The game selects a random word from a predefined list.
- Letter Guessing: Players guess one letter at a time.
- Hint System: Players can request hints to reveal a letter.
- Score Tracking: Players earn points based on remaining attempts.
- Responsive Design: The game is designed to work on all screen sizes.
- Animations: Fun animations for correct and incorrect guesses.
Step 2: Styling with CSS
To make our game visually appealing, we will use CSS to style the interface.
body {
font-family: 'Arial', sans-serif;
background-color: #f4f4f9;
color: #333;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
.container {
text-align: center;
background-color: #fff;
padding: 2rem;
border-radius: 10px;
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}
h1 {
font-size: 2.5rem;
margin-bottom: 1rem;
color: #2c3e50;
}
#word-display {
font-size: 2rem;
letter-spacing: 0.5rem;
margin: 1.5rem 0;
color: #27ae60;
}
#guess-input {
padding: 0.5rem;
font-size: 1rem;
border: 2px solid #3498db;
border-radius: 5px;
width: 70px;
text-align: center;
}
#guess-btn, #hint-btn, #reset-btn {
padding: 0.5rem 1rem;
font-size: 1rem;
border: none;
border-radius: 5px;
cursor: pointer;
margin: 0.5rem;
}
#guess-btn {
background-color: #3498db;
color: white;
}
#guess-btn:hover {
background-color: #2980b9;
}
#hint-btn {
background-color: #9b59b6;
color: white;
}
#hint-btn:hover {
background-color: #8e44ad;
}
#reset-btn {
background-color: #e74c3c;
color: white;
}
#reset-btn:hover {
background-color: #c0392b;
}
#message {
margin-top: 1rem;
font-size: 1.2rem;
color: #e74c3c;
}
#attempts {
font-weight: bold;
color: #e67e22;
}
#score {
font-weight: bold;
color: #2ecc71;
}
/* Animations */
@keyframes shake {
0% { transform: translateX(0); }
25% { transform: translateX(-5px); }
50% { transform: translateX(5px); }
75% { transform: translateX(-5px); }
100% { transform: translateX(0); }
}
.shake {
animation: shake 0.5s;
}
@keyframes bounce {
0% { transform: translateY(0); }
50% { transform: translateY(-10px); }
100% { transform: translateY(0); }
}
.bounce {
animation: bounce 0.5s;
}
This CSS file:
Centers the game on the page.
Gives it a clean, modern look with rounded borders and shadows.
Sets up text styles for easy readability.
Step 3: JavaScript Logic for the Game
The JavaScript will implement the game logic, including selecting a random word, tracking guesses, and updating the display.
const words = ["javascript", "html", "css", "developer", "programming", "openai"];
let selectedWord = words[Math.floor(Math.random() * words.length)];
let guessedWord = Array(selectedWord.length).fill("_");
let attemptsLeft = 6;
let score = 0;
const wordDisplay = document.getElementById("word-display");
const guessInput = document.getElementById("guess-input");
const guessBtn = document.getElementById("guess-btn");
const hintBtn = document.getElementById("hint-btn");
const resetBtn = document.getElementById("reset-btn");
const message = document.getElementById("message");
const attemptsDisplay = document.getElementById("attempts");
const scoreDisplay = document.getElementById("score");
// Function to reveal some letters based on word length
function revealLetters() {
const wordLength = selectedWord.length;
let lettersToReveal;
if (wordLength <= 4) {
lettersToReveal = 1; // For short words, reveal 1 letter
} else if (wordLength <= 6) {
lettersToReveal = 2; // For medium words, reveal 2 letters
} else {
lettersToReveal = 3; // For longer words, reveal 3 letters
}
// Reveal random letters
for (let i = 0; i < lettersToReveal; i++) {
const hiddenLetters = guessedWord
.map((letter, index) => (letter === "_" ? index : null))
.filter((index) => index !== null);
if (hiddenLetters.length > 0) {
const randomIndex = hiddenLetters[Math.floor(Math.random() * hiddenLetters.length)];
guessedWord[randomIndex] = selectedWord[randomIndex];
}
}
}
// Initialize the game
function initializeGame() {
selectedWord = words[Math.floor(Math.random() * words.length)];
guessedWord = Array(selectedWord.length).fill("_");
attemptsLeft = 6;
revealLetters(); // Reveal letters based on word length
wordDisplay.textContent = guessedWord.join(" ");
attemptsDisplay.textContent = attemptsLeft;
message.textContent = "";
guessInput.disabled = false;
guessBtn.disabled = false;
hintBtn.disabled = false;
}
// Display the initial word with some revealed letters
initializeGame();
This script:
Selects a random word from a predefined list.
Displays it as underscores (_ _ _ _ ) to represent hidden letters.
Initializes game variables like attempts and score.
Step 4: Implementing the Guessing Logic
When a user inputs a letter, the game checks if it is correct and updates the word display accordingly.
// Guess button functionality
guessBtn.addEventListener("click", () => {
const guess = guessInput.value.toLowerCase();
guessInput.value = "";
if (!guess || !/[a-z]/.test(guess)) {
showMessage("Please enter a valid letter.", "shake");
return;
}
if (selectedWord.includes(guess)) {
// Update the guessed word with the correct letter
selectedWord.split("").forEach((letter, index) => {
if (letter === guess) {
guessedWord[index] = guess;
}
});
wordDisplay.textContent = guessedWord.join(" ");
showMessage("Correct guess!", "bounce");
} else {
attemptsLeft--;
attemptsDisplay.textContent = attemptsLeft;
showMessage(`Incorrect! ${attemptsLeft} attempts left.`, "shake");
}
// Check for win or lose
if (guessedWord.join("") === selectedWord) {
score += attemptsLeft * 10; // Add points based on remaining attempts
scoreDisplay.textContent = score;
showMessage("Congratulations! You guessed the word!", "bounce");
disableInput();
} else if (attemptsLeft === 0) {
showMessage(`Game over! The word was "${selectedWord}".`, "shake");
disableInput();
}
});
This function:
Takes user input and checks if it is a valid letter.
Updates the guessed word if correct.
Reduces attempts if incorrect.
Step 5: Adding the Hint Feature
The hint button will reveal a random letter from the hidden word to help the player.
// Hint button functionality
hintBtn.addEventListener("click", () => {
const hiddenLetters = guessedWord
.map((letter, index) => (letter === "_" ? index : null))
.filter((index) => index !== null);
if (hiddenLetters.length > 0) {
const randomIndex = hiddenLetters[Math.floor(Math.random() * hiddenLetters.length)];
guessedWord[randomIndex] = selectedWord[randomIndex];
wordDisplay.textContent = guessedWord.join(" ");
showMessage(`Hint: Letter "${selectedWord[randomIndex]}" revealed!`, "bounce");
} else {
showMessage("No hints needed!", "shake");
}
});
This feature reveals a random letter from the hidden word when the user clicks the hint button.
Step 6: Reset Button to Restart the Game
Clicking the eset button will start a new game with a different word.
// Reset button functionality
resetBtn.addEventListener("click", initializeGame);
This ensures that when the user clicks reset, the game starts over with a new word.
Additionally, we use the showMessage function to display feedback messages and the disableInput function to prevent further input once the game is won or lost.
function showMessage(msg, animation) {
message.textContent = msg;
message.classList.remove("shake", "bounce");
message.classList.add(animation);
}
function disableInput() {
guessInput.disabled = true;
guessBtn.disabled = true;
hintBtn.disabled = true;
}
// Initialize score display
scoreDisplay.textContent = score;
full script.js
// script.js
const words = ["javascript", "html", "css", "developer", "programming", "openai"];
let selectedWord = words[Math.floor(Math.random() * words.length)];
let guessedWord = Array(selectedWord.length).fill("_");
let attemptsLeft = 6;
let score = 0;
const wordDisplay = document.getElementById("word-display");
const guessInput = document.getElementById("guess-input");
const guessBtn = document.getElementById("guess-btn");
const hintBtn = document.getElementById("hint-btn");
const resetBtn = document.getElementById("reset-btn");
const message = document.getElementById("message");
const attemptsDisplay = document.getElementById("attempts");
const scoreDisplay = document.getElementById("score");
// Function to reveal some letters based on word length
function revealLetters() {
const wordLength = selectedWord.length;
let lettersToReveal;
if (wordLength <= 4) {
lettersToReveal = 1; // For short words, reveal 1 letter
} else if (wordLength <= 6) {
lettersToReveal = 2; // For medium words, reveal 2 letters
} else {
lettersToReveal = 3; // For longer words, reveal 3 letters
}
// Reveal random letters
for (let i = 0; i < lettersToReveal; i++) {
const hiddenLetters = guessedWord
.map((letter, index) => (letter === "_" ? index : null))
.filter((index) => index !== null);
if (hiddenLetters.length > 0) {
const randomIndex = hiddenLetters[Math.floor(Math.random() * hiddenLetters.length)];
guessedWord[randomIndex] = selectedWord[randomIndex];
}
}
}
// Initialize the game
function initializeGame() {
selectedWord = words[Math.floor(Math.random() * words.length)];
guessedWord = Array(selectedWord.length).fill("_");
attemptsLeft = 6;
revealLetters(); // Reveal letters based on word length
wordDisplay.textContent = guessedWord.join(" ");
attemptsDisplay.textContent = attemptsLeft;
message.textContent = "";
guessInput.disabled = false;
guessBtn.disabled = false;
hintBtn.disabled = false;
}
// Display the initial word with some revealed letters
initializeGame();
// Guess button functionality
guessBtn.addEventListener("click", () => {
const guess = guessInput.value.toLowerCase();
guessInput.value = "";
if (!guess || !/[a-z]/.test(guess)) {
showMessage("Please enter a valid letter.", "shake");
return;
}
if (selectedWord.includes(guess)) {
// Update the guessed word with the correct letter
selectedWord.split("").forEach((letter, index) => {
if (letter === guess) {
guessedWord[index] = guess;
}
});
wordDisplay.textContent = guessedWord.join(" ");
showMessage("Correct guess!", "bounce");
} else {
attemptsLeft--;
attemptsDisplay.textContent = attemptsLeft;
showMessage(`Incorrect! ${attemptsLeft} attempts left.`, "shake");
}
// Check for win or lose
if (guessedWord.join("") === selectedWord) {
score += attemptsLeft * 10; // Add points based on remaining attempts
scoreDisplay.textContent = score;
showMessage("Congratulations! You guessed the word!", "bounce");
disableInput();
} else if (attemptsLeft === 0) {
showMessage(`Game over! The word was "${selectedWord}".`, "shake");
disableInput();
}
});
// Hint button functionality
hintBtn.addEventListener("click", () => {
const hiddenLetters = guessedWord
.map((letter, index) => (letter === "_" ? index : null))
.filter((index) => index !== null);
if (hiddenLetters.length > 0) {
const randomIndex = hiddenLetters[Math.floor(Math.random() * hiddenLetters.length)];
guessedWord[randomIndex] = selectedWord[randomIndex];
wordDisplay.textContent = guessedWord.join(" ");
showMessage(`Hint: Letter "${selectedWord[randomIndex]}" revealed!`, "bounce");
} else {
showMessage("No hints needed!", "shake");
}
});
// Reset button functionality
resetBtn.addEventListener("click", initializeGame);
function showMessage(msg, animation) {
message.textContent = msg;
message.classList.remove("shake", "bounce");
message.classList.add(animation);
}
function disableInput() {
guessInput.disabled = true;
guessBtn.disabled = true;
hintBtn.disabled = true;
}
// Initialize score display
scoreDisplay.textContent = score;
Conclusion
We've successfully built a Word Guessing Game together! You can now play the game and even modify it to add more features like difficulty levels or sound effects.