Javascript Hangman:用正确的字母替换空格的麻烦

时间:2018-12-05 01:45:52

标签: javascript jquery

所以我在游戏的特定部分遇到了麻烦。这些是我的初始变量:

var words = ["sugar","banana","hulk"];
var guessLeft = 12;
var wrongGuess = [];
var hiddenWord = [];
var hiddenWordText = document.getElementById("hiddenword-text");
var chosenWord = words[Math.floor(Math.random() * words.length)];

到目前为止,从我的数组中正确选择一个随机单词,并用与所选单词长度相同的下划线替换它们是正确的。这是我的操作方式:

for (i = 0; i < chosenWord.length; i++) {
    hiddenWord.push("_");
    hiddenWordText.textContent = hiddenWord.join(" ");
}

现在,当我弄清楚我的猜测是否与字母匹配时,我遇到的麻烦是如何用猜测的字母替换正确的下划线索引。

到目前为止,这是我所掌握的,而且我不确定自己是否走对了。有人有任何提示吗?或者您可以引导我正确的方向吗?

document.onkeyup = function(event) {
    var userGuess = event.key;

    if (chosenWord.indexOf(userGuess) >= 0){
        for (var i = 0; i < wordLength; i++){
            if (chosenWord[i] == userGuess){
                hiddenWord[i] == userGuess;

                hiddenWordText.textContent = hiddenWord[i] + hiddenWord;
            }
        }
    }
    else {
        guessLeft = guessLeft - 1;
    }
}

2 个答案:

答案 0 :(得分:3)

您的代码中有几个错误

使用=代替==进行变量分配

在循环后用textContext替换hiddenWordText的{​​{1}},在该循环中已显示正确猜出的单词。以前,您会在每次循环迭代时都替换hiddenWord.join(" "),这将忽略先前迭代中找到的匹配项

textContext

答案 1 :(得分:2)

与其试图找出hiddenWord中的下划线是否需要替换为真实字母,不如将到目前为止已选择的字母数组替换为负字符集。一个正则表达式,并从真正的输入单词中,用下划线替换该集中的所有字符 not 。例如:

const chosenWord = 'banana';

const guesses = [];
// when a user guesses a letter, push it to guesses:
// example, user guesses "a" and "b":
guesses.push('a');
guesses.push('b');

// then, when you need to display the partially-filled-in word:
const pattern = new RegExp(
  '[^' + guesses.join('') + ']', 'g'
);

// in this case, the pattern will look like:
//    [^ab]
// which means, match any characters that are not "a" nor "b"


// Replace all characters that are neither "a" nor "b" with an underscore:
const wordToDisplay = chosenWord.replace(pattern, '_');
console.log(wordToDisplay);
// hiddenWordText.textContent = wordToDisplay;