var words = ["javascript", "monkey", "amazing", "pancake"];
var word = words[Math.floor(Math.random() * words.length)];
var answerArray = []; //selected word
for (var i = 0; i < word.length; i++){
answerArray[i] = "*";
}
//cheat: check the word is
console.log(word);
var life = 5;
//get word length
var remainingLetters = word.length;
while(remainingLetters > 0 && life > 0){
//show the player their progress
var el = document.getElementById("top");
el.innerHTML = answerArray.join(" ");
//get a guess form the player
var guess_str = "Guess a letter";
var word_str = "\nThe Word is: " + answerArray.join(" ");
var word_length_str = "\nThe Word length is: "+ word.length;
var remaining_letters_str = "\nThe remaining letters is: " + remainingLetters;
var life_str = "\nYou have " + life + " life.";
var guess = prompt(guess_str.concat(word_str, word_length_str, remaining_letters_str, life_str));
//process
if (guess.length !== 1) {
alert("Please enter one letter")
// loops through the word and if found a correct letter, the star will be relaced with the letter and the remaining letters will decrease by one.
}
else {
//wrong guess
if(word.indexOf(guess) == -1){
life--;
//alert("Life = " + life);
}
//correct guess
else{
//replace correct character with answer
for (var j = 0; j < word.length; j++){
if (word[j] == guess){
answerArray[j] = guess;
remainingLetters--;
}
}
//alert("Remaining Letters: " + remainingLetters);
}
}
}
//win or lose
if(life > 0){
alert("You have won.");
}
else{
alert("You have lost.");
}
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.