word-guess-1

JavaScript game for kids

HTML

<div id="output"></div>
<input type="submit" id="byBtn" value="Hint !" onclick="showHint()" />

JavaScript

var output = document.getElementById('output');
document.getElementById('byBtn').onclick = function() {
  showHint();
}

var wordToGuess = "American Flag";

var hints = [];

var hiddenWord = "";

//var myVar = setInterval(showHint, 1000);

for (i = 0; i < wordToGuess.length; i++) {
  if (wordToGuess.charAt(i) == " ") {
    hints.push("&nbsp;");
  } else {
    hints.push("_");
  }
}

hiddenWord = hints.join(" ");
output.innerHTML = hiddenWord;

//while (bad_guesses !== 3 && hints.indexOf("_") !== -1) {
showHint();

function showHint() {


  do {
    var guess = wordToGuess.toUpperCase().charAt(Math.floor(Math.random() * wordToGuess.length));


    if (wordToGuess.toUpperCase() == hints.join("").replace(/&nbsp;/g, " ")) {
    clearInterval(myVar);
      alert("Word complete");
      return;
    }
  }
  while (hiddenWord.indexOf(guess) > -1);

  if (hiddenWord.indexOf(guess) > -1) {
    // alert(guess + " found");
  } else {
    // alert(guess + " not found");
  }

  if (wordToGuess.toUpperCase().indexOf(guess) === -1) {} else {
    for (i = 0; i < wordToGuess.length; i++) {
      if (wordToGuess[i].toUpperCase() === guess) {
        if (!(guess == " ")) {
          hints[i] = guess;
        }
      }
    }
  }

  // Output
  hiddenWord = hints.join(" ");
  output.innerHTML = hiddenWord;
}