如何调试控制台Hangman程序?

时间:2016-05-30 14:11:14

标签: javascript

该程序将句子作为用户输入。然后它随机选择刽子手游戏的单词。要求用户逐个输入字母。我相信我的功能guess有问题。它的行为并不像我想要的那样。

猜猜函数假设guess(letter)。如果尚未尝试使用letter,请将尝试的字母推入guessedLetters数组并减少猜测1.循环显示currentWord以查看字母是否匹配。如果是,请将信件分配给hangmanWord中的相应位置。

如果isOver返回true,则调用overMessage,否则调用render,提示新字母使用该字母调用guess(使用递归)。

var numOfGuesses;
var gueesedLetters = []
var currentWord = ''
var hangmanWord = []
var letter;

function guess(letter) {
    if (gueesedLetters.indexOf(letter) === -1) {
        gueesedLetters.push(letter);
        numOfGuesses--;
    }
    else {
        for (var i = 0; i < currentWord.length; i++) {
            if (letter === currentWord[i]) {
                var currWrdIndex = currentWord.indexOf(letter)
                hangmanWord.splice(currentWord[i], 0, letter)
            }
        }
    }


    if (isOver() === true) {
        overMessage();
    } else {
        console.log(render());
        letter = prompt("Please enter the letter").toLowerCase();
        guess(letter);
    }
}


function isOver() {
    if (currentWord.split("").sort().join("") === hangmanWord.sort().join("") || numOfGuesses === 0) {
        return true
    } else {
        return false
    }
}

function overMessage() {
    if (currentWord.split().sort().join("") === hangmanWord.sort().join("")) {
        return "You win";
    } else if (numOfGuesses === 0) {
        return "You lose";
    } else {
        return "Game is not over";
    }
}

function render() {
    console.log("The hangman word was %s", currentWord);
    console.log("The total number of guesses are %s", numOfGuesses);
    console.log("Total guess letters are %s", gueesedLetters);

}


function startGame(wordsArray) {
    numOfGuesses = 10;
    gueesedLetters = []
    currentWord = wordsArray[Math.floor(Math.random() * wordsArray.length)]
    letter = prompt("Please enter the letter ?")
    guess(letter);
}

function mainProgram() {
    var userSentence = prompt("Please enter sentences to begin.")
    userSentence = userSentence.split(" ")
    startGame(userSentence)
    if (isOver() === true) {
        console.log(overMessage())
        console.log(render())
    }
}

mainProgram()

0 个答案:

没有答案