连续检查 4 个数组

Check array on 4 in a row

我有这个数组,我想连续检查 4 个(游戏)。我可以用数百个 if else 来做,但我怎么能循环做呢?这可能吗? 这是我的代码。提前致谢!

int array[][] = {{0, 1, 1, 1, 1, 0, 0},
                 {0, 0, 0, 1, 0, 1, 1},
                 {0, 0, 0, 1, 0, 1, 1},
                 {0, 1, 1, 0, 1, 0, 1},
                 {1, 0, 0, 1, 0, 1, 1},
                 {1, 0, 0, 1, 0, 1, 0}};

for (int rows = 0; rows < 6; rows++) {
    for(int columns = 0; columns < 7; columns++) {
        System.out.print(array[rows][columns] + " ");
    }
    System.out.println();
}

if (array[0][0] == 0) {
    if(array[0][1] == 0) {
        if (array[0][2] == 0) {
            if (array[0][3] == 0) {
                System.out.println("Connect Four!");
            }
        }
    }
}

是这样的吗?

int[] dx = {0, 1, 0, -1}; // I think you only need the first two, because
int[] dy = {1, 0, -1, 0}; // otherwise you check things twice

for (int y = 0; y < array.length; y++) {
    for (int x = 0; x < array[y].length; x++) {
        int start_value = array[y][x];
        for (int i = 0; i < dx.length; i++) {
            for (int j = 1; j < 4; j++) {
                // check if there are enough cells in y direction
                if (y + dy[i] * j >= array.length) break;
                // check if there are enough cells in x direction
                if (x + dx[i] * j >= array[y].length) break;
                // check if the value is the same
                if (array[y + dy[i] * j][x + dx[i] * j] != start_value) {
                    break;
                }
                // the next three elements in a direction are the same
                if (j == 3) {
                    System.out.println("4 in a row");
                    return;
                }
            }
        }
    }
}
System.out.println("not 4 in a row");

如果您想检查更多方向,例如对角线,请向 dxdy 添加更多值。

我会引入一个计数器,每当您当前的数字为 0 时,它就会增加 "line",如果当前数字为 1,则重置它。如果计数器达到 4,则您连接了 4 个。

看看这个:

int array[][] = {{0, 1, 1, 1, 1, 0, 0},
                 {0, 0, 0, 1, 0, 1, 1},
                 {0, 0, 0, 1, 0, 1, 1},
                 {0, 1, 1, 0, 1, 0, 1},
                 {1, 0, 0, 1, 0, 1, 1},
                 {1, 0, 0, 1, 0, 1, 0}};

//Search rows
for (int i = 0; i < array.length; i++) {
    int rowCount = 0;                   
    for (int j = 0; j < array[i].length; j++) {
        if (array[i][j] == 0) {
            rowCount++;
        } else {
            rowCount = 0;
        }
        if (rowCount == 4) {
            System.out.println("yay");
        }
    }
}

这不是完整的代码,仅针对行。但它应该能让您了解如何解决行甚至对角线的问题。