我正在JS / jQuery中创建一个Hangman游戏(有一个扭曲)。我已经弄清楚如何根据用户输入(当他们猜一个字母时)识别被猜测的单词数组的索引。但是,我无法弄清楚如何获取该索引并将空白(underscoreArray)替换为同一索引处的用户输入值。
我尝试使用条件(在JS代码的末尾)执行此操作,但我不确定如何使其工作。
在正确猜测后,此条件应该更改html(例如,如果单词是"拖动"并且用户猜测" d")" _ _ _ _"到" d _ _ _"。
这是fiddle,这是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();
};
}
});
});
});
答案 0 :(得分:2)
有一些问题:
[word]
不会生成字符数组。使用word.split('')
。underscores
字符串设置为包含空格,使其长度为word
的两倍,因此index
需要乘以2来补偿indexOf
只返回第一个这应该更接近:
var wordArray = word.split('');
var underscoresArray = underscores.split('');
for (var i = 0; i < wordArray.length; i++) {
// Catch every letter, eg. the "p"s in "popcorn"
if (wordArray[i] == guess) {
// Underscored indices are twice the word indices
// "popcorn" -> "p _ p _ _ _ _"
underscoresArray[i * 2] = guess;
};
}
// Only need to do this once after all changes are made
underscores = underscoresArray.join(''); // Collapse back to string
$('#words').after(underscores);
console.log(underscores);
答案 1 :(得分:1)