Programming help
I'm following a book on how to make a hangman game but I don't really understand how each line of code works could someone explain to me what each line of code does. The book just confuses me. Thank you!
Code:
<!DOCTYPE html>
<html>
<head>
<title>Hangman</title>
</head>
<body style="background-color:#DE81E4">
<script>
// Create an array of words
var words = ["venture", "exaggerate", "guilt", "agent", "love", "happy", "film", "waist", "weeds", "movies", "clap", "acting", "lion", "programming", "family", "drop", "rainbow", "sprinkles", "computer", "chair", "theater", "blanket", "cookies", "guests", "television", "rabbit", "tornado", "house", "popcorn"];
// pick a random word from the words array
var word = words[Math.floor(Math.random() * words.length)];
// set up the answerArray to show how many letters there are in the word
var answerArray = [];
for (var i = 0; i < word.length; i++) {
answerArray[i] = "_";
}
// Create a variable to hold the number of remainingLetters to be guessed
var remainingLetters = word.length;
// ******************** THE MAIN GAME LOOP ********************
// While there are letters still to be guessed
while (remainingLetters > 0) {
// Show they player there progress
alert(answerArray.join(" "));
// Get a guess from the player
var guess = prompt("Guess the letter or Click cancel to stop playing");
// If the guess is blank
if (guess == null) {
// Exit the game
break;
// if the guess is more than one letter
} else if (guess.length !== 1) {
// Alert them to guess only one letter
alert("Please enter a single letter");
// Vaild guess
}
else {
// Update the game
for (var j = 0; j < word.length; j++) {
// if the lettr they guessed is in the word at that point or index
if (word[j] === guess) {
// update the answer array with the letter they guessed
answerArray[j] = guess;
// subtract one from remaining letters
remainingLetters--;
}
}
}
// ******************** END OF GAME LOOP ********************
}
// Let the player know the word
alert(answerArray.join(" "));
// congrat them
alert("Good job! If you guessed the word...That's great! if not don't worry you will get the HANG of it. The word was" + word);
</script>
</body>
</html>
Please sign in to leave a comment.