JavaScript - Hangman - 逻辑问题

时间:2017-04-24 13:42:39

标签: code.org app-lab

我试图让我的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");
});

我已附加代码,以及包含链接以查看应用程序的运行情况。

Here's a link to the app

提前致谢!

1 个答案:

答案 0 :(得分:0)

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);