Hangman Game in HTML - Play Online Now
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
- Copy and paste the HTML code into a new HTML file (e.g.,
hangman.html). - Open the file in a web browser.
- Enter a letter in the text box and click "Guess."
- Repeat step 3 until you guess the word or run out of guesses.
- If you win, an alert will appear saying "You win!" The game will then restart.
- If you lose, an alert will appear saying "You lose!" The game will then restart.
Have fun playing Hangman!
原文地址: https://www.cveoy.top/t/topic/lmpw 著作权归作者所有。请勿转载和采集!