我目前正在尝试获取二维数组的对角行。
这是数组的样子:
/* Array containing the playing field 8 x 8
C0 C1 C2 C3 C4 C5 C6 C7
R0[0][0][0][0][0][0][0][X]
R1[0][0][0][0][0][0][X][0]
R2[0][0][0][0][0][X][0][0]
R3[0][0][0][0][X][0][0][0]
R4[0][0][0][X][0][0][0][0]
R5[0][0][X][0][0][0][0][0]
R6[0][X][0][0][0][0][0][0]
R7[X][0][0][0][0][0][0][0]
*/
row0 = [0, 0, 0, 0, 0, 0, 0, 0],
row1 = [0, 0, 0, 0, 0, 0, 0, 0],
row2 = [0, 0, 0, 0, 0, 0, 0, 0],
row3 = [0, 0, 0, 0, 0, 0, 0, 0],
row4 = [0, 0, 0, 0, 0, 0, 0, 0],
row5 = [0, 0, 0, 0, 0, 0, 0, 0],
row6 = [0, 0, 0, 0, 0, 0, 0, 0],
row7 = [0, 0, 0, 0, 0, 0, 0, 0];
field = [row0, row1, row2, row3, row4, row5, row6, row7];
我正在尝试检查游戏玩家是否连续有四个。当前处理水平和垂直检查的功能将获得以下信息:
用户单击的列ID和行ID(函数中的x表示玩家编号)
这是我用来检查的功能:
function checkVieropeenrij(id, rij, x) {
function contains(hooibaal, naalden) {
return hooibaal.join(",").indexOf(naalden.join(",")) != -1;
}
var horizontaal = field[0, rij];
var verticaal = [];
for (g=7; g>=0; g--) {
verticaal[g] = field[g][id-1]
}
var diagonaal = []
var needles = [x, x, x, x];
if (contains(horizontaal, needles) || contains(verticaal, needles)) {
spelActief = false;
return true
}
else if (!contains(horizontaal, needles) || !contains(verticaal, needles)) {
return false
}
}
所以我想做的是将[X,X,X,X,X,X,X,X,X]存储在一个新数组(变量diagonaal_1)中,我正在寻找最有效的方法。
对角线的位置取决于玩家单击的位置,因此,如果他们单击C6,R6,则应该从R7,C5到R0,C7以及从R7,C7到R0,C0的对角线(存储在整个游戏场上的对角线)在单独的vars中)
最佳答案
该建议将给定位置移动到数组的相对顶部,并沿给定方向收集项目。
基本上,它首先检查是否有移动空间,并且在收集时是否要收集空间。
var height = 8,
width = 8,
field = [
[0, 1, 4, 0, 0, 0, 3, 0],
[0, 4, 1, 0, 0, 3, 0, 0],
[4, 0, 0, 1, 3, 0, 0, 0],
[0, 0, 0, 3, 1, 0, 0, 0],
[0, 0, 3, 0, 0, 1, 0, 0],
[2, 3, 0, 0, 0, 0, 1, 0],
[3, 2, 0, 0, 0, 0, 0, 1],
[0, 0, 2, 0, 0, 0, 0, 0]
];
function getBackSlash(i, j) { // direction \
var result = [];
while (i > 0 && j > 0) { // is space to move (top/left)?
i--;
j--;
}
while (i < height && j < width) { // are items in the range to collect?
result.push(field[i][j]);
i++;
j++;
}
return result;
}
function getSlash(i, j) { // direction /
var result = [];
while (i > 0 && j + 1 < width) { // is space to move (top/right)?
i--;
j++;
}
while (i < height && j >= 0) { // are items in the range to collect?
result.push(field[i][j]);
i++;
j--;
}
return result;
}
document.write('<pre>1: [' + getBackSlash(3, 4).join(', ') + ']</pre>');
document.write('<pre>2: [' + getBackSlash(7, 2).join(', ') + ']</pre>');
document.write('<pre>3: [' + getSlash(3, 3).join(', ') + ']</pre>');
document.write('<pre>4: [' + getSlash(0, 2).join(', ') + ']</pre>');