我正在尝试获取一个嵌套的forEach循环,该循环在二维数组中找到一对四个。
这是我的数组的示例:
[0, 0, 0, 0, 0],
[0, 2, 0, 0, 0],
[0, 1, 2, 0, 0],
[0, 1, 2, 2, 0],
[1, 2, 1, 1, 2],
它应该忽略0,而只能找到四个水平的,垂直的和对角的对,每个对具有“1”或“2”。
有人有什么建议吗?
最佳答案
乔纳斯(Jonas)的答案比这个答案更好,但是如果您不理解他的语法,这是一个简化且冗长的版本:
var field = [
[0, 0, 0, 0, 0],
[0, 2, 0, 0, 0],
[0, 1, 2, 0, 0],
[0, 1, 2, 2, 0],
[1, 2, 1, 1, 2]
];
function checkVertical(field, player){
for(i = 0; i < 5; ++i){
if (field[0][i] === player
&& field[1][i] === player
&& field[2][i] === player
&& field[3][i] === player
) return true;
if (field[1][i] === player
&& field[2][i] === player
&& field[3][i] === player
&& field[4][i] === player
) return true;
}
return false;
}
function checkHorizontal(field, player){
for(i = 0; i < 5; ++i){
if (field[i][0] === player
&& field[i][1] === player
&& field[i][2] === player
&& field[i][3] === player
) return true;
if (field[i][1] === player
&& field[i][2] === player
&& field[i][3] === player
&& field[i][4] === player
) return true;
}
return false;
}
function checkDiagonal1(field, player){
// exercise for the reader
return false;
}
function checkDiagonal2(field, player){
// exercise for the reader
return false;
}
function isWin(field, player){
return checkVertical(field, player)
|| checkHorizontal(field, player)
|| checkDiagonal1(field, player)
|| checkDiagonal2(field, player);
}
console.log(isWin(field, 1));