Hangman Game in HTML

This code creates a basic Hangman game using HTML, JavaScript, and CSS. It allows you to guess a word by entering letters one at a time. You have 6 chances to guess the word correctly before you lose.

HTML Code

<!DOCTYPE html>
<html>
<head>
  <title>Hangman Game</title>
</head>
<body>
  <h1>Hangman Game</h1>
  <p>Guess the word by entering a letter:</p>
  <input type='text' id='guessInput'>
  <button onclick='guessLetter()'>Guess</button>
  <p id='wordToGuess'></p>
  <p id='remainingGuesses'></p>
  <script>
    // List of words to choose from
    const words = ['apple', 'banana', 'orange', 'grape', 'kiwi'];

    // Select a random word from the list
    const word = words[Math.floor(Math.random() * words.length)];

    // Create an array to store the word as dashes
    const wordArray = Array(word.length).fill('-');

    // Display the word as dashes
    document.getElementById('wordToGuess').innerHTML = wordArray.join(' ');

    // Set the number of remaining guesses
    let remainingGuesses = 6;
    document.getElementById('remainingGuesses').innerHTML = `Remaining Guesses: ${remainingGuesses}`;

    function guessLetter() {
      // Get the letter input by the user
      const letter = document.getElementById('guessInput').value;

      // Check if the letter is in the word
      if (word.includes(letter)) {
        // Replace the dashes with the letter
        for (let i = 0; i < word.length; i++) {
          if (word[i] === letter) {
            wordArray[i] = letter;
          }
        }
        document.getElementById('wordToGuess').innerHTML = wordArray.join(' ');
      } else {
        // Decrement the remaining guesses
        remainingGuesses--;
        document.getElementById('remainingGuesses').innerHTML = `Remaining Guesses: ${remainingGuesses}`;
      }

      // Check if the user has won or lost
      if (!wordArray.includes('-')) {
        alert('You win!');
        location.reload();
      } else if (remainingGuesses === 0) {
        alert(`You lose! The word was ${word}.`);
        location.reload();
      }
    }
  </script>
</body>
</html>

How to Play

  1. Copy and paste the HTML code into a new HTML file (e.g., hangman.html).
  2. Open the file in a web browser.
  3. Enter a letter in the text box and click "Guess."
  4. Repeat step 3 until you guess the word or run out of guesses.
  5. If you win, an alert will appear saying "You win!" The game will then restart.
  6. If you lose, an alert will appear saying "You lose!" The game will then restart.

Have fun playing Hangman!

Hangman Game in HTML - Play Online Now

原文地址: https://www.cveoy.top/t/topic/lmpw 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录