I am currently working on a game where users have to guess a word by selecting the right symbol from the alphabet. When the user guesses correctly, the code is supposed to replace all placeholders with the correct character, but in the wrong order.
var secretWord = document.getElementById('secretWord'); //id of div element
var targetWord = "example"; // the word to be guessed
for (var i = 0; i < targetWord.length; i++) {
secretWord.innerHTML += '<span class="lineStyle">_ </span>';
} // creates a pattern for guessing
The following code checks if the clicked character matches:
for (var j = 0; j < keys.length; j++){
keys[j].addEventListener('click', function(){
var letter = this.innerHTML;
var count = 0;
var matched = 0;
for (count = 0; count < targetWord.length; count++) {
if (letter == targetWord.charAt(count)) {
secretWord.innerHTML = secretWord.innerHTML.replace('_ ', letter);
matched++;
} else if (letter != targetWord.charAt(count)) {
secretWord.innerHTML = secretWord.innerHTML.replace('_ ', '_ ');
}
}
if (matched == 0) {
incorrectGuess();
}
});
}
The goal is for the user to reveal each correct letter in the right sequence when they click on it. For instance:
1) If the word is "example"
2) The display shows: _ _ _ _ _ _ _
3) User clicks on "a"
4) Display changes to: "_ a _ _ _ _ _
"
However, my code currently displays: "a a _ _ _ _ _
"