检查连续4个数组

时间:2016-01-13 12:58:50

标签: java arrays loops connect

我有这个数组,我想连续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}};

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!");
            }
        }
    }
}

2 个答案:

答案 0 :(得分:3)

这样的东西?

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添加更多值。

答案 1 :(得分:0)

我会介绍一个计数器并在每次当前&#34;线&#34;如果当前数字是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");
        }
    }
}

这不是完整的代码,仅适用于行。但它应该让你知道如何解决行甚至是对角线的问题。

相关问题