Dwebs Abstract

Hangman Game with JavaScript: A Step-by-Step Tutorial

By Pranav Choudhary, Dwebs Tutorial | Last Updated: 02-05-2024

Post Image

In this tutorial, we'll guide you through the process of creating a Hangman game using JavaScript. Hangman is a classic word-guessing game where players attempt to guess a secret word by suggesting letters within a certain number of attempts. By building this game, you'll not only have fun but also gain valuable experience in JavaScript programming and DOM manipulation.

  1. Setting Up the Structure:To start, we'll outline the structure of our Hangman game. This involves creating the necessary HTML elements to display the game interface, including the secret word, the hangman drawing, letters to guess, and a form for player input. Organizing the layout effectively will ensure a seamless gaming experience for players.

  2. Generating a Random Word:One of the essential elements of Hangman is the secret word that players must guess. We'll write JavaScript code to select a random word from a predefined list. This random word will serve as the target for players to guess throughout the game. Choosing an extensive list of words ensures replayability and keeps the game challenging and engaging.

  3. Displaying the Secret Word:In the game interface, we'll create placeholders to represent each letter of the secret word. Initially, these placeholders will appear as underscores to indicate the length of the word. As players guess correct letters, we'll reveal them in the appropriate positions of the word. This step requires dynamic updating of the HTML content based on player input.

  4. Handling Player Input:To enable player interaction, we'll implement functionality to handle player input. This involves adding event listeners to the letter buttons displayed on the screen. When a player selects a letter, we'll check if it matches any of the letters in the secret word. Proper validation and feedback mechanisms ensure a smooth and intuitive gameplay experience.

  5. Implementing Game Logic:We'll incorporate game logic to track the player's progress and determine the outcome of each guess. This includes counting the number of incorrect guesses, updating the hangman drawing accordingly, and determining when the game is won or lost. Effective game logic ensures a fair and challenging experience for players.

  6. Enhancing the User Experience:To elevate the user experience, we'll add visual and auditory elements to our Hangman game. Styling the game interface with CSS improves aesthetics, while animations and sound effects enhance immersion. Additionally, we'll consider implementing features such as a scoreboard, hints, or difficulty levels to cater to different player preferences.

Create a file named index.html and paste the below code there.

The below code is .Html file.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <link rel="stylesheet" href="style.css" />
    <title>Hangman</title>
  </head>
  <body>
    <h1>Hangman</h1>
    <p>Find the hidden word - Enter a letter</p>
    <div class="game-container">
      <svg height="250" width="200" class="figure-container">
        <!-- Rod -->
        <line x1="60" y1="20" x2="140" y2="20" />
        <line x1="140" y1="20" x2="140" y2="50" />
        <line x1="60" y1="20" x2="60" y2="230" />
        <line x1="20" y1="230" x2="100" y2="230" />

        <!-- Head -->
        <circle cx="140" cy="70" r="20" class="figure-part" />
        <!-- Body -->
        <line x1="140" y1="90" x2="140" y2="150" class="figure-part" />
        <!-- Arms -->
        <line x1="140" y1="120" x2="120" y2="100" class="figure-part" />
        <line x1="140" y1="120" x2="160" y2="100" class="figure-part" />
        <!-- Legs -->
        <line x1="140" y1="150" x2="120" y2="180" class="figure-part" />
        <line x1="140" y1="150" x2="160" y2="180" class="figure-part" />
      </svg>

      <div class="wrong-letters-container">
        <div id="wrong-letters"></div>
      </div>

      <div class="word" id="word"></div>
    </div>

    <!-- Container for final message -->
    <div class="popup-container" id="popup-container">
      <div class="popup">
        <h2 id="final-message"></h2>
        <h3 id="final-message-reveal-word"></h3>
        <button id="play-button">Play Again</button>
      </div>
    </div>

    <!-- Notification -->
    <div class="notification-container" id="notification-container">
      <p>You have already entered this letter</p>
    </div>

    <script src="script.js"></script>
  </body>
</html>

Create a file named style.css and paste the below code there.

The below code is .Css file.

* {
  box-sizing: border-box;
}

body {
  background-color: #34495e;
  color: #fff;
  font-family: Arial, Helvetica, sans-serif;
  display: flex;
  flex-direction: column;
  align-items: center;
  height: 80vh;
  margin: 0;
  overflow: hidden;
}

h1 {
  margin: 20px 0 0;
}

.game-container {
  padding: 20px 30px;
  position: relative;
  margin: auto;
  height: 350px;
  width: 450px;
}

.figure-container {
  fill: transparent;
  stroke: #fff;
  stroke-width: 4px;
  stroke-linecap: round;
}

.figure-part {
  display: none;
}

.wrong-letters-container {
  position: absolute;
  top: 20px;
  right: 20px;
  display: flex;
  flex-direction: column;
  text-align: right;
}

.wrong-letters-container p {
  margin: 0 0 5px;
}

.wrong-letters-container span {
  font-size: 24px;
}

.word {
  display: flex;
  position: absolute;
  bottom: 10px;
  left: 50%;
  transform: translateX(-50%);
}

.letter {
  border-bottom: 3px solid #2980b9;
  display: inline-flex;
  font-size: 30px;
  align-items: center;
  justify-content: center;
  margin: 0 3px;
  height: 50px;
  width: 20px;
}

.popup-container {
  background-color: rgba(0, 0, 0, 0.3);
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  /* display: flex; */
  display: none;
  align-items: center;
  justify-content: center;
}

.popup {
  background: #2980b9;
  border-radius: 5px;
  box-shadow: 0 15px 10px 3px rgba(0, 0, 0, 0.1);
  padding: 20px;
  text-align: center;
}

.popup button {
  cursor: pointer;
  background-color: #fff;
  color: #2980b9;
  border: 0;
  margin-top: 20px;
  padding: 12px 20px;
  font-size: 16px;
}

.popup button:active {
  transform: scale(0.98);
}

.popup button:focus {
  outline: 0;
}

.notification-container {
  background-color: rgba(0, 0, 0, 0.3);
  border-radius: 10px 10px 0 0;
  padding: 15px 20px;
  position: absolute;
  bottom: -50px;
  transition: transform 0.3s ease-in-out;
}

.notification-container p {
  margin: 0;
}

.notification-container.show {
  transform: translateY(-50px);
}

Create a file named script.js and paste the below code there.

The below code is .Js file.

const wordEl = document.getElementById('word');
const wrongLettersEl = document.getElementById('wrong-letters');
const playAgainBtn = document.getElementById('play-button');
const popup = document.getElementById('popup-container');
const notification = document.getElementById('notification-container');
const finalMessage = document.getElementById('final-message');
const finalMessageRevealWord = document.getElementById('final-message-reveal-word');

const figureParts = document.querySelectorAll('.figure-part');

const words = ['application', 'programming', 'interface', 'wizard'];

let selectedWord = words[Math.floor(Math.random() * words.length)];

let playable = true;

const correctLetters = [];
const wrongLetters = [];

// Show hidden word
function displayWord() {
	wordEl.innerHTML = `
    ${selectedWord
			.split('')
			.map(
				letter => `
          <span class="letter">
            ${correctLetters.includes(letter) ? letter : ''}
          </span>
        `
			)
			.join('')}
  `;

	const innerWord = wordEl.innerText.replace(/[ \n]/g, '');

	if (innerWord === selectedWord) {
		finalMessage.innerText = 'Congratulations! You won! 😃';
		finalMessageRevealWord.innerText = '';
		popup.style.display = 'flex';

		playable = false;
	}
}

// Update the wrong letters
function updateWrongLettersEl() {
	// Display wrong letters
	wrongLettersEl.innerHTML = `
    ${wrongLetters.length > 0 ? '<p>Wrong</p>' : ''}
    ${wrongLetters.map(letter => `<span>${letter}</span>`)}
  `;

	// Display parts
	figureParts.forEach((part, index) => {
		const errors = wrongLetters.length;

		if (index < errors) {
			part.style.display = 'block';
		} else {
			part.style.display = 'none';
		}
	});

	// Check if lost
	if (wrongLetters.length === figureParts.length) {
		finalMessage.innerText = 'Unfortunately you lost. 😕';
		finalMessageRevealWord.innerText = `...the word was: ${selectedWord}`;
		popup.style.display = 'flex';

		playable = false;
	}
}

// Show notification
function showNotification() {
	notification.classList.add('show');

	setTimeout(() => {
		notification.classList.remove('show');
	}, 2000);
}

// Keydown letter press
window.addEventListener('keydown', e => {
	if (playable) {
		if (e.keyCode >= 65 && e.keyCode <= 90) {
			const letter = e.key.toLowerCase();

			if (selectedWord.includes(letter)) {
				if (!correctLetters.includes(letter)) {
					correctLetters.push(letter);

					displayWord();
				} else {
					showNotification();
				}
			} else {
				if (!wrongLetters.includes(letter)) {
					wrongLetters.push(letter);

					updateWrongLettersEl();
				} else {
					showNotification();
				}
			}
		}
	}
});

// Restart game and play again
playAgainBtn.addEventListener('click', () => {
	playable = true;

	//  Empty arrays
	correctLetters.splice(0);
	wrongLetters.splice(0);

	selectedWord = words[Math.floor(Math.random() * words.length)];

	displayWord();

	updateWrongLettersEl();

	popup.style.display = 'none';
});

displayWord();

Conclusion

By following this step-by-step tutorial, you'll have successfully created a Hangman game using JavaScript. Building games not only hones your programming skills but also provides an opportunity for creativity and innovation. Whether you're a beginner or an experienced developer, crafting interactive games like Hangman is a rewarding and enjoyable endeavor. Have fun coding and happy gaming!

"Keep your eyes peeled for upcoming projects that will supercharge your development journey and propel your skills to new heights!"

Live ViewDownload Code

Recommended Posts

Dwebs Image

Start Your Own Social Media Management Agency: A Step-by-Step Guide

STARTUP
WFH

In today's digital age, the importance of a strong social media presence for businesses cannot be overstated. As platforms like Facebook, Instagram, and Twitter continue to dominate the online landscape, the demand for expert social media management services is at an all-time high. If you have a passion for social media and a knack for strategy, starting your own Social Media Management Agency could be the perfect entrepreneurial venture. In this guide, we'll walk you through the essential steps.

Dwebs Image

Credit Card Fraud Detection | Machine Learning Project

PYTHON

In today's digital era, where financial transactions are predominantly conducted online, the risk of credit card fraud has escalated significantly. According to a report by the Federal Trade Commission (FTC), credit card fraud was the most common type of identity theft reported in 2020, accounting for 39% of all identity theft reports. To combat this growing threat, financial institutions and payment processors are increasingly turning to advanced technologies such as machine learning (ML).