我试图在2D阵列中对角搜索四连体游戏。我以为我知道了,但是显然我错了。第一组for循环可以正常工作,对角地从右到左搜索。第二组for循环不起作用。我以为我要做的就是将一些积极的迹象转变为消极的事情,并且奏效。最终,通过更改GRID_HEIGHT-1 ... BUT,我得以使其部分工作,但我不断遇到错误。在这一点上的任何帮助将不胜感激。同样,二维数组的网格为5x4。所以它真的连接3。
for (int y = 0; y <= GRID_HEIGHT-3; y++) {
for (int x = 0; x <= GRID_WIDTH-3; x++) {
if (
state[y][x] != Player.NONE &&
state[y][x] == state[y+1][x+1] &&
state[y+1][x+1] == state[y+2][x+2]
) return state[y][x];
}
}
for (int y = 0; y <= GRID_HEIGHT-3; y++) {
for (int x = 0; x <= GRID_WIDTH-3; x++) {
if (
state[y][x] != Player.NONE &&
state[y][x] == state[y-1][x-1] &&
state[y-1][x-1] == state[y-1][x-2]
) return state[y][x];
}
}
return Player.NONE;
}
对于第二组循环,您将从索引中减去,这意味着索引可以低于零。您需要循环才能从零开始。
for (int y = 2; y < GRID_HEIGHT; y++) {
for (int x = 2; x < GRID_WIDTH; x++) {
if (
state[y][x] != Player.NONE &&
state[y][x] == state[y-1][x-1] &&
state[y-1][x-1] == state[y-2][x-2]
) return state[y][x];
}
}
另外,通常在适用时应说(x <GRID_HEIGHT)而不是(x <= GRID_HEIGHT-1),因为秒读起来比较困难。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句