1 //hangman 2 let numGuesses = 10; 3 let word = prompt("Type in a word or leave blank for a random word."); 4 if (!word) 5 { 6 let words = ["JavaScript", "science", "pony", "Earth"]; 7 let index = Math.floor(Math.random() * words.length); 8 word = words[index]; 9 } 10 11 word = word.toUpperCase(); 12 let playerWord = []; 13 14 for (let i = 0; i < word.length; i++) 15 { 16 playerWord.push("-"); 17 } 18 19 while (playerWord.indexOf("-") >= 0 && numGuesses > 0) 20 { 21 let message = playerWord.join(" "); 22 message += " Guess a letter."; 23 24 let guess = prompt(message); 25 guess = guess[0].toUpperCase(); 26 27 let wrongGuess = true; 28 for (let j = 0; j < word.length; j++) 29 { 30 if (word[j] === guess) 31 { 32 playerWord[j] = guess; 33 wrongGuess = false; 34 } 35 } 36 if (wrongGuess) 37 { 38 alert(guess + " is not in the word."); 39 numGuesses--; 40 } 41 } 42 43 alert("The word was " + word + "."); 44 if (numGuesses > 0) 45 { 46 alert("You won!"); 47 } 48 else 49 { 50 alert("Better luck next time."); 51 } 52