Diagonal win checks in Connect 4 [duplicate]

淺唱寂寞╮ 提交于 2019-12-12 03:23:53

问题


I am developing a Connect 4 game with 7x7 fields, horizontal and vertical checks but I dont get diagonal checks works

I can win as long as one of the tokens is not in the last column.

This are all checks:

private static int getWinningInDiagonals() {

    // Top-Left -> Bottom-Right
    for (int column = 0; column < 7; column++) {
        int count = 0;
        for (int row = 0; row < 7; row++) {
            if (field[row][column] != 0 && field[row+1][column + row - 1] == field[row][column])
                count++;
            else
                count = 1;
            if (count >= 4) {
                return field[row][column];
            }                   
        }
    }
    // Top-Right -> Bottom-Left
    for (int column = 0; column < 7; column++) {
        int count = 0;
        for (int row = 0; row < 7; row++) {
            if (field[row][column] != 0 && field[row+1][column - row + 1] == field[row][column])
                count++;
            else
                count = 1;
            if (count >= 4) {
                return field[row][column];
            }
        }
    }        
    return 0;
}

回答1:


For one you want to move down and right at the same time every time, you also only need to go to 3, 3 as a diagonal cannot occur any farther than that without it leaving the bounds of the array.

This should work for your top left to bottom rights if I'm right in assuming that your top left is your 0,0. Doing top right to bottom left is a matter of changing the column and row loops and changing how the offset works.

// Top-Left -> Bottom-Right
for (int column = 0; column < 4; column++) {
    for (int row = 0; row < 4; row++) {
        player = 0;
        if (field[row][column] != 0){
            player=field[row][column];
            offset = 1;
        }
        while (player != 0){
            if (field[row + offset][column + offset] == player){
                offset += 1;
            }else{
                player = 0;
            }
        }                   
        if(offset >= 4){
            return field[row][column];
        }
    }
}


来源:https://stackoverflow.com/questions/33291238/diagonal-win-checks-in-connect-4

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!