连续检测对角线胜利-井字游戏,五子棋

时间:2019-08-22 19:47:24

标签: java algorithm

在Gomoku上进行的游戏中,玩家必须连续获得5个才能赢。检测对角线赢是个问题。

我尝试了下面的代码,该代码从右上方搜索2d矩阵,直到找到我们正在寻找的玩家令牌,例如如图1所示,它随后从该点对角线进行搜索以找到获胜的行。如果算法遇到的第一个“ 1”是获胜路线的一部分,则此方法效果很好。如果不是,而只是一个随机数,则该算法将返回false,因为它不会继续搜索。

伊塔克怎么会最后玩游戏,而只搜索与该动作有关的对角线?或可能编辑提供的代码以搜索整个电路板。

public boolean is_diagonal_win_left(int player) {
    int i = 0;
    for (int col = board_size-1; col > (win_length - 2); col--) {
        for (int row = 0; row < board_size-(win_length-1); row++) {
            while (board_matrix[row][col] == player) {
                i++;
                row++;
                col--;
                if (i == win_length) return true;
            }
            i = 0;
        }
    }
    return false;
}

//solved

public boolean is_diagonal_win_right(int player, int r, int c) {

        int count = 0;
        int row = r;
        int col = c;

        while ((row != 0) && (col != 0)) {
            row--;
            col--;
        }

        while ((row <= board_size - 1) && (col <= board_size - 1)) {
            if (board_matrix[row][col] == player) count++;
            row++;
            col++;
        }

        return count == win_length;
    }

1 个答案:

答案 0 :(得分:2)

您是正确的:在板子上搜索第一个计数器无效;搜索整个电路板是浪费时间。从最近的动作开始。我们将该位置称为(r, c);玩家的令牌仍为player。检查八个功能说明中的每一个,以查看player的字符串有多长时间。例如,您可以像这样检查NW-SE对角线:

count = 1     // We just placed one counter
row = r-1; col = c-1
while ( (row >= 0) and (col >= 0) and 
        (board_matrix[row][col] == player) )
    count += 1

row = r+1; col = c+1
while ( (row < board_size) and (col < board_size) and 
        (board_matrix[row][col] == player) )
    count += 1

// Note: gomoku rules require exactly 5 in a row;
//   if you're playing with a"at least 5", then adjust this to >=
if (count == win_length) {
    // Process the win
}