西蒙说游戏无法禁用彩色垫在电脑回合

Simon Says Game unable to disable color pads during computer turn

本文关键字:电脑 彩色 游戏 西蒙      更新时间:2023-09-26

我已经构建了simon游戏。它的功能正确,如果用户播放正确,但在试图使它充分证明,我想禁用用户点击选择,而计算机正在显示下一个模式。我已经尝试了许多使用jquery .on/的组合。.unbind/。绑定e.c preventdefault,但是没有成功。有人能帮我解决这个问题吗?这是一个代码独立的链接,如果你想看到完整的项目,因为我只打算张贴什么似乎是相关的代码下面。http://codepen.io/RawleJuglal/full/vKxwWw/

HTML:

<div class='gameContainer'>
   <div class="center"></div>
   <a href="#" id="1" class="field blue"></a>
   <a href="#" id="2" class="field yellow "></a>
   <a href="#" id="3" class="field red"></a>
   <a href="#" id="4" class="field green"></a> 
</div><!--End of gameContainer--> 
CSS:

function playComputerSequence(seq,speed){
  //Preventing pressing not working
  $('.field').each(function(){
     $(this).off('click',function(e){
        e.preventDefault();
     });
  });
  //Everything below this working correctly
  var count = Number($('.count span').text());
  var i = 0;
  var interval = setInterval(function(){
     $('#'+seq[i]).addClass('on');
     var audio = new Audio(audioArray[seq[i]-1]);
     setTimeout(function(){
        audio.play();
        $('#'+seq[i]).removeClass('on');
        i++;
     },500)
     setTimeout(function(){
        if(i == count)
        {
           clearInterval(interval);
        }
     },500);
  },speed);
  $('.field').each(function(){
     $(this).off().on('click',recordUserChoice);
  });
}
function recordUserChoice(){
  userArray.push(this.id);
  var audio = new Audio(audioArray[this.id-1]);
  setTimeout(function(){
     audio.play();
  },500);
  checkSequence(userArray);
}

我的建议是使用某种标志来确定游戏的状态。

显然,.off()没有做到这一点,所以我会说删除所有对它的引用。然而,我相信它不起作用的原因是因为你用错了。解除绑定时不需要使用.each()。这就是选择器的作用,所以如果你使用$('.field').off('click', '**'),应该从class='field'的任何元素中删除所有委托的点击处理程序。要了解正确的用法,我建议查看这里:http://api.jquery.com/off/

然而,我仍然不认为你应该删除委派的事件。为了简化事情,我们只需要设置一个可以查看游戏状态的标志。

var gameState = 0; //0 means the user can click, 1 means the user cannot
function playComputerSequence(seq, speed){
   gameState = 1;
   //Rest of function code
   //...
   gameState = 0;
}
function recordUserChoice(){
   if(gameState === 1) return; //if gameState is 1, jump out of the function
   //Rest of function code
   //...
}

虽然这个逻辑是有效的,但需要根据您的情况进行稍微不同的调整。

在代码的开头,在audioArray下面放置以下代码。这将是您的field点击处理程序。

$(document).on('click', '.field', recordUserChoice);

然后,我意识到的一件事是gamestate基本上立即变回0,所以我把它放在你clearInterval(interval)的下面,因为这是决定计算机何时完成的。

if(i == count)
{
   clearInterval(interval);
  gamestate = 0;
  console.log(gamestate);
}

可以删除$('.field').each()的所有实例

见此笔:http://codepen.io/anon/pen/wWJLyp