首页 > 解决方案 > XO 游戏(我如何证明玩家一(p1)或玩家二(p2)如果满足(var winBoxes)中的条件之一获胜

问题描述

如果他达到(var winBoxes)中的条件之一,我如何证明玩家一(p1)或玩家二(p2)获胜。

var counter = 0;
var p1=[];
var p2=[];
var winBoxes = [
        [box1, box2, box3],
        [box1, box4, box7],
        [box2, box5, box8],
        [box3, box6, box9],
        [box4, box5, box6],
        [box7, box8, box9],
        [box1, box5, box9],
        [box3, box5, box7]
       ];

     //Start the click function 
     $('.boxes div').one('click',function(){

    counter += 1;
    if(counter %2 === 0){
        $(this).text('X');
        p1.push($(this).attr('id'));

       }else{

           $(this).text('O');
           p2.push($(this).attr('id'));
       }
    });

Codepen上有完整的代码

标签: javascriptjquery

解决方案


您需要首先创建一个单独的函数来检查一个数组是否是另一个数组的子数组。

function isSubsetOf(big, small){
  return small.every(x => big.includes(x));
}

然后在框中的每次更改中,您需要检查其中的任何数组winBoxes是否是任何p1和的子数组p2。满足条件的玩家将获胜。

  if(winBoxes.some(a => isSubsetOf(p1, a))){
    console.log("p1 wins")
  }
  if(winBoxes.some(a => isSubsetOf(p2, a))){
    console.log("p2 wins")
  }

工作代码在这里Codepen


推荐阅读