用户点击速度过快的错误

时间:2018-11-25 00:19:15

标签: javascript

首先,我是JS的新手。 我正在尝试制作记忆游戏,但我有下一个问题。 代码:

function cardClicked(elCard) {
  // If the user clicked an already flipped card - do nothing and return from the function
  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) {
    elPreviousCard = elCard;

  } else {
    // 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) {

        setTimeout(function () {
            elCard.classList.remove('flipped');
            elPreviousCard.classList.remove('flipped');
            elPreviousCard = null;
        }, 1000)
        wrongPick.play();
    } else {
        // Yes! a match!
        flippedCouplesCount++;
        elPreviousCard = null;
        rightPick.play();
    }
}

我想阻止用户单击两次以上(这是一个记忆游戏)。有人可以告诉我如何将其实现到我的代码中吗?

3 个答案:

答案 0 :(得分:0)

您可以将全局变量设置为isClickable,最初将其设置为true,然后输入代码检查其是否为true,如果不是,则返回,否则返回,否则继续将其设置为false,并进行超时以将其再次设置为true ,例如:

var isClickable = true;
function cardClicked(elCard) {
  if (!isClickable) return;
  isClickable = false;
  setTimeout(function () {
    isClickable = true;
  }, 500)
...

答案 1 :(得分:0)

由于是纸牌游戏,因此我将执行以下操作: 制作元素数组:

var cards = (
    {
     "card":"numberOfCard",
     "isclicked" :"yes/no"
    }
);

然后每当有人点击卡片时,我都会将isClickable更改为no,因此下次发生事件时,我会阻止它。

答案 2 :(得分:0)

例如创建变量opened_cards,该变量存储打开的卡的数量,如果少于2个则允许打开另一张卡,否则不执行任何操作。

var opened_cards = 0;

function cardClicked(elCard) {
  // do check here
  if (opened_cards < 2) {
    // less than 2 card opened do operation 
    opened_cards++;
    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) {
      elPreviousCard = elCard;

    }
    else {
      // 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) {

        setTimeout(function() {
          opened_cards -= 2;
          elCard.classList.remove('flipped');
          elPreviousCard.classList.remove('flipped');
          elPreviousCard = null;
        }, 1000);
        wrongPick.play();
      }
      else {
        // Yes! a match!
        opened_cards = 0;
        flippedCouplesCount++;
        elPreviousCard = null;
        rightPick.play();
      }
    }
  }
}