如何解决此浏览器游戏错误

时间:2019-10-27 02:19:10

标签: javascript

游戏中的错误是,如果用户单击速度足够快,则他可以翻转2张以上的卡。 我试图使这个布尔变量(var isProcessing)并将其在代码的某些位置设置为true / false, 但我认为我在某些地方放错了位置,因为该错误似乎并未得到解决。

我在哪里放错了布尔值,哪里出错了?

代码:

// Those are global variables, they stay alive and reflect the state of the game
var elPreviousCard = null;
var flippedCouplesCount = 0;

// This is a constant that we dont change during the game (we mark those with CAPITAL letters)
var TOTAL_COUPLES_COUNT = 3;

// Load an audio file
var audioWin = new Audio('sound/win.mp3');
var audioright = new Audio('sound/right.mp3');
var audiowrong = new Audio('sound/wrong.mp3');
var isProcessing = false;
// This function is called whenever the user click a card
function cardClicked(elCard) {

    // If the user clicked an already flipped card - do nothing and return from the function
    isProcessing = true;
    if (elCard.classList.contains('flipped')) {
        return;
    }
    // Flip it
    elCard.classList.add('flipped');

    // This is a first card, only keep it in the global variable
    if (elPreviousCard === null) {
        isProcessing = true;
        elPreviousCard = elCard;
    } else {
        isProcessing = false;
        // get the data-card attribute's value from both cards
        var card1 = elPreviousCard.getAttribute('data-card');
        var card2 = elCard.getAttribute('data-card');

        // No match, schedule to flip them back in 1 second
        if (card1 !== card2){
            isProcessing = false;
            setTimeout(function () {
                elCard.classList.remove('flipped');
                elPreviousCard.classList.remove('flipped');
                elPreviousCard = null;
                isProcessing = true;
            }, 1000)
            audiowrong.play();


        } else {
            // Yes! a match!
            flippedCouplesCount++;
            elPreviousCard = null;
            audioright.play();

            // All cards flipped!
            if (TOTAL_COUPLES_COUNT === flippedCouplesCount) {
                audioWin.play();

                // and finally add a button to call resetCard() 
        document.getElementById("Play Again").innerHTML =
        '<button onclick="resetCard();">Play Again</button>';
            }

        }

    }

}

function resetCard() {// to erase the flipped classes
    var cardclass = document.getElementsByClassName("card");
    for (i = 0; i < cardclass.length; i++) {
      cardclass[i].classList.remove("flipped");
      document.getElementById("Play Again").innerHTML = "";
    }
}

0 个答案:

没有答案