Play Hangman Online - Free HTML Game
<html>
<head>
<title>Play Hangman Online - Free HTML Game</title>
</head>
<body>
<h1>Let's Play Hangman!</h1>
<div id="word"></div>
<div id="wrongLetters"></div>
<div>
<button id="tryLetter">Try Letter</button>
</div>
<script>
// This is the word that the player is trying to guess
const word = 'hangman';
// This is the number of tries the player has before they lose
const tries = 7;
// This is the array of letters that have been guessed incorrectly
let wrongLetters = [];
// This is the array of letters that have been guessed correctly
let correctLetters = [];
// This is the HTML element that will display the word
const wordElement = document.getElementById('word');
// This is the HTML element that will display the incorrect letters
const wrongLettersElement = document.getElementById('wrongLetters');
// This is the HTML element that will be used to try a letter
const tryLetterElement = document.getElementById('tryLetter');
<pre><code> // This will add an event listener to the try letter button
tryLetterElement.addEventListener('click', () => {
// This is the letter that the player is trying to guess
let letter = prompt('What letter do you want to guess?');
// Check if the letter is in the word
if (word.indexOf(letter) >= 0) {
// Add the letter to the correct letters array
correctLetters.push(letter);
// Update the word element with the new correct letter
wordElement.innerHTML = getWordElement();
} else {
// Add the letter to the wrong letter array
wrongLetters.push(letter);
// Update the wrong letter element
wrongLettersElement.innerHTML = wrongLetters.join(', ');
// Subtract one from the amount of tries left
tries--;
// Check if the player has any tries left
if (tries <= 0) {
// If not, alert the player that they have lost
alert('You lost!');
}
}
});
// This will create the word element
function getWordElement() {
let output = '';
// Loop through each letter in the word
for (let i = 0; i < word.length; i++) {
// Check if the letter has been guessed
if (correctLetters.indexOf(word[i]) >= 0) {
// If so, add the letter to the output
output += word[i];
} else {
// Otherwise, add an underscore
output += '_';
}
}
// Return the output
return output;
}
</script>
</body>
</code></pre>
</html>
原文地址: https://www.cveoy.top/t/topic/lmpy 著作权归作者所有。请勿转载和采集!