简体   繁体   English

在二维数组中搜索对角线

[英]Searching diagonal in a 2d array

I am trying to search diagonally in a 2D array for a connect four game. 我试图在2D阵列中对角搜索四连体游戏。 I thought I had it figured out, but apparently I am wrong. 我以为我知道了,但是显然我错了。 The first set of for loops work fine, searching right to left, diagonally. 第一组for循环工作正常,对角地从右到左搜索。 The second set of for loops, do not work. 第二组for循环不起作用。 I thought all i had to do was switch some positive signs to negative and it work. 我以为我要做的就是将一些积极的迹象转变为消极的事情,并且奏效。 Eventually, I was able to get it to work partially, by changing the GRID_HEIGHT-1...BUT, I keep getting bound errors. 最终,通过更改GRID_HEIGHT-1 ... BUT,我得以使其部分工作,但我不断遇到错误。 Any help at this point would be greatly appreciated. 在这一点上的任何帮助将不胜感激。 Also, the grid for the 2d array is 5x4. 同样,二维数组的网格为5x4。 So its really connect 3. 所以它真的连接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 the second set of loops, you are subtracting from the indexes, which means that the index can go below zero. 对于第二组循环,您将从索引中减去,这意味着索引可以低于零。 You need the loop to start above zero. 您需要循环才能从零开始。

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];
    }
}

Also, generally you should be saying (x < GRID_HEIGHT) rather than (x <= GRID_HEIGHT-1) when applicable as the second is harder to read. 此外,通常在适用时应说(x <GRID_HEIGHT)而不是(x <= GRID_HEIGHT-1),因为秒读起来比较困难。

GRID_HEIGHT向下迭代到GRID_HEIGHT-3 ,而不是从0迭代到GRID_HEIGHT-3 3。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM