javascript - 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上有完整的代码
解决方案
您需要首先创建一个单独的函数来检查一个数组是否是另一个数组的子数组。
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
推荐阅读
- sparql - Wikidata:仅过滤当前有效的邮政编码
- android - 如何在 MacBook M1 上的 Android 模拟器中为 API 30 和 29 获取 ARM 64?
- opencascade - 如何找到构成 stp 文件面的顶点和三角形
- authentication - ASP.Net Core MVC IdentityFrameWork 不工作
- javascript - 如何通过创建反应应用启用 JIT(即时模式)?
- javascript - 如何在数据表中使用输入字段添加最小和最大范围过滤器?
- powershell - 如何在 PowerShell 中执行 curl 命令以从 JFrog Artifactory 下载文件而不调用 cmd.exe?
- javascript - Javascript倒计时以获取当前间隔时间运行
- node.js - TDengine数据库nodejs连接器毫秒精度
- python - 为什么我添加的特殊标记没有在掩码语言建模中显示为预测?