2017-04-24 75 views
0

我試圖讓我的Hang子手遊戲檢查是否在該單詞中找到該字母,但截至目前它正在檢查該單詞的每個字符中是否找到該字母。第一次猜測後,我不會再猜測。JavaScript - Hangman - Logic Issue

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

在此先感謝!

回答

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