I am creating a Hangman game (with a twist) in JS/jQuery. I have figured out how to identify the index of the array of the word being guessed based on the user input (when they guess a letter). However, I cannot figure out how to take that index and replace the blank (underscoreArray) with the value of the user input at the same index.
I have tried to do this with a a conditional (at the end of the JS code), but I'm not sure how to make this work.
Upon a correct guess, this conditional should change the html from (for example, if the word is "drag" and the user guesses "d") " _ _ _ _ " to "d _ _ _".
Here is the fiddle and here is the JS:
$(document).ready(function() {
var words = ["shade", "she mail", "queen"];
var usedLetters = [];
var wrongLetters = [];
$('.play').click(function() {
var word = words[Math.floor(Math.random() * words.length)];
var wordLength = word.length;
var underscores = "";
for (i = 0; i < wordLength; i++) {
underscores = underscores + "_ ";
}
$('.btn-default').on('click', function() {
var guess = $(this).text();
if (jQuery.inArray(guess, usedLetters) === -1) {
usedLetters.push(guess);
$('.used').html('<p class="used">Letters used:</p><span>' + usedLetters + '</span>');
} else {
alert("You already guessed \"" + guess + "\"!");
}
/*Find out if guess = an index of word, and if it does replce the underscore index with the guess*/
var find = word.indexOf(guess);
var wordArray = [word];
//loop through wordArray and where wordArray === find replace same index of underscores with guess.
for (i = 0; i < wordArray.length; i++) {
var underscoresArray = [underscores];
var index = wordArray.indexOf(guess);
if (index !== -1) {
underscoresArray[index] = guess;
$('#words').after(underscoresArray).toString();
};
}
});
});
});
[]syntax converts a string into a list of characters. When you're doing[word]you're creating a list of 1 element, namely 'word'. What you need to do is create a list of characters of your word, which you can do by using thesplit()method:var characters = word.split('');