JavaScript - 刽子手 - 逻辑问题

JavaScript - Hangman - Logic Issue

我正在尝试让 Hangman 游戏检查是否在单词中找到该字母,但截至目前,它正在检查是否在单词的每个字符中都找到了该字母。它不允许我在第一次猜测后再次猜测。

setScreen("WelcomeScreen");
//variables
var WordArray = ["apple", "word", "quiz"];
var currentWord = ""; 
var wrongCounter = 0;
var bodyPartCounter = 0; 
var Guess = "";
//Welcome Screen Code
onEvent("letsGoBtn", "click", function () {
  setScreen("playingHangmanScreen");
  generateWord(); 
  setUpScreenElements();
});

function generateWord() {
  currentWord = WordArray[randomNumber(0,2)];
  console.log(currentWord);
}
function setUpScreenElements(){
  for (var i = 0; i < currentWord.length; i++) {
    showElement("letterArea" + [i]);
  }
  var showCorrectHint = "hintWord" + currentWord;
  showElement(showCorrectHint);
  console.log(showCorrectHint);
}
//Guessing Code
onEvent("submitBtn", "click", function () {
  Guess = getText("guessInputTxt");
  console.log("The guess for " + currentWord + " is: " + Guess);
  checkGuess();
});

function checkGuess() {
    for (var i = 0; i < currentWord.length; i++) {
      if (Guess == currentWord.charAt([i])) {
        setText("letterArea" + [i], Guess);
        console.log("Correctly guessed letter is: " + currentWord.charAt([i]));
      } 
      else {
        wrongCounter++;
        console.log("wrongCounter for " + currentWord + " is: " + wrongCounter);
        if (wrongCounter == currentWord.length) {
          bodyPartCounter++;
          showElement("wrongGuessImg" + bodyPartCounter);
          setText("livesLeftNumber", (6-bodyPartCounter));
        }
        if (bodyPartCounter === 6) {
          setScreen("gameOverScreen");
        }
      }
    } 
    resetGuessInput();
  }

function resetGuessInput () {
  setText("guessInputTxt", " ");
  Guess = " ";
  wrongCounter = 0;
}
//Game Over Screen and Play Again Button
onEvent("playAgainBtn", "click", function () {
  hideElement("hintWord" + currentWord);
  generateWord();
  setUpScreenElements();
  setScreen("playingHangmanScreen");
  for (var i = 0; i <currentWord.length; i++) {
    setText("letterArea" + [i], " ");
  }
  for (var j = 1; j < 7; j++) {
    hideElement("wrongGuessImg" + [j]);
  }
  bodyPartCounter = 0;
  wrongCounter = 0;
  setText("livesLeftNumber", "6");
});
//Victory Screen 
onEvent("goHomeBtn", "click", function() {
  setScreen("WelcomeScreen");
});

我附上了代码,并附上了 link 以查看应用程序的运行情况。

Here's a link to the app

提前致谢!

checkGuess函数需要先判断字母在单词中出现(或不出现)的位置,然后更新一次棋盘,而不是每个字符都更新一次:

function checkGuess() {
  var foundAtIndex = -1;
  for (var i = 0; i < currentWord.length; i++) {
    if (Guess == currentWord.charAt([i])) {
      foundAtIndex = i;
      break;
    }
  }

  if (foundAtIndex >= 0) {
    setText("letterArea" + [foundAtIndex], Guess);
    // etc...

幸运的是,Javascript 为字符串提供了一个很好的 IndexOf 函数,因此您可以完全删除循环并将第一部分压缩为:

var foundAtIndex = currentWord.indexOf(Guess);