如果在Javascript Hangman游戏中正确,如何用字母替换占位符字符?

时间:2018-06-15 03:26:09

标签: javascript

对于我的生活,我无法理解这一点,我的newGame函数以及我的letterGuess函数,但在letterGuess函数中检查的for循环除外

pickedWord

表示如果按下的.onkeyup字母是随机选择的单词中的正确字母。我一直在盯着这个,似乎无法弄清楚出了什么问题......我在做什么有什么不对,或者有没有更好的办法呢?

var newGameButton = document.getElementById('new-game-button');
var placeholders = document.getElementById('placeholders');
var guessedLetters = document.getElementById('guessed-letters');
var guessesLeft = document.getElementById('guesses-left');
var wins = document.getElementById('wins');
var losses = document.getElementById('losses');

var wordBank = [
    "html", 
    "css",
    "javascript",
    "reactjs",
    "nodejs",
    "ruby",
    "python",
    "pancakes",
];
var wins = 0;
var losses = 0;
var guessesLeft = 20;
var gameRunning = false;
var pickedWord = '';
var pickedWordPlaceholderArr = [];
var guessedLetterBank = [];
var incorrectLetterBank = [];

function newGame() {
    gameRunning = true;
    guessesLeft = 20;
    pickedWordPlaceholderArr = [];
    guessedLetterBank = [];
    incorrectLetterBank = [];

// Pick random word
    var pickedWord = wordBank[Math.floor(Math.random() * wordBank.length)];

// Create placeholders out of pickedWord
    for (var i = 0; i < pickedWord.length; i++) {
      if (pickedWord[i] === ' ') {
        pickedWordPlaceholderArr.push(' '); 

    } 
}

guessesLeft.textContent = guessesLeft;
placeholders.textContent = pickedWordPlaceholderArr.join('');
guessedLetters.textContent = incorrectLetterBank;
}   


function letterGuess(letter) {
    console.log(letter);

    if (gameRunning === true && guessedLetterBank.indexOf(letter) === -1) {
        // Run game logic
        guessedLetterBank.push(letter);

        for (var i = 0; i < pickedWord.length; i++) {
            if (pickedWord[i].toLowerCase() === letter.toLowercase()) {
                // If match, replace with letter
                pickedWordPlaceholderArr[i] = pickedWord[i];
            } 
            else {
                console.log("something went wrong")
            }
        }

        console.log(pickedWordPlaceholderArr);
        console.log(guessedLetterBank);
        placeholders.textContent = pickedWordPlaceholderArr.join('');
    }
    else {
        if (!gameRunning) {
            alert("Game not running");
        } else {
            alert("Already guessed letter");
        }
    }
}

newGameButton.addEventListener('click', newGame);

document.onkeyup = function(event) {
    console.dir(event);
    if (event.keyCode >= 65 && event.keyCode <= 90) {
        letterGuess(event.key)
    }
}

0 个答案:

没有答案