【发布时间】:2018-06-29 12:48:39
【问题描述】:
我正在构建一个井字游戏。我目前正在尝试编写函数来检查是否有人赢得了比赛。我有一个包含一组数据的对象,其中包括一个多维数组,其中包含与棋盘上的方块相关的获胜“数字”的所有组合。每次你点击一个方格时,方格的编号都会被推送到每个玩家的单独数组中。
我目前的问题是循环并找出包含玩家当前方格的数组何时等于中奖号码数组之一。
我已经尝试了很多不同的方法,包括嵌套 for 循环的不同变体、使用包含、使用 indexOf,然后尝试控制台记录获胜消息或将随机值推送到单独的数组/变量当达到 3 表示胜利时,但实际上我现在精神崩溃了,希望任何人都可以提供任何建议。
var game = {
player: true,
win: [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,5],[2,5,8],[0,4,8],[2,4,6]],
//the above is my array of winning combinations
p1Points: 0,
p2Points: 0,
p1Moves:[], //the place for players "moves" to be stored
p2Moves:[]
}
function currentMove(square){
var squareNum = square.data('squarenumber');
square.off();
if(game.player){
square.html('x');
game.p1Moves.push(squareNum);
game.player = false;
checkWin(game.win, game.p1Moves)
}
else{
square.html('0');
game.p2Moves.push(squareNum);
game.player = true;}
checkWin(game.win, game.p2Moves)
}
function checkWin(winArr, movesArr){
/* this is the function I need help with, have tried multiple things
it needs to return somthing to signal a player has won. e.g three in a
row. */
}
【问题讨论】:
-
你可以添加你最好的尝试,只是为了找出你的搜索出了什么问题。
-
当然很抱歉,我只是想重写我最好的,我是在一个 codepen 中完成的,它不会回溯到足够远的地方让我找到,所以现在就再去一次吧
标签: javascript jquery arrays for-loop