在NXN Tic Tac Toe游戏中确定获胜者

时间:2015-01-17 23:23:55

标签: java multidimensional-array tic-tac-toe

我尝试使用play和hasWon方法创建一个Tic Tac Toe游戏类。

public class TicTacToe {

private enum State{Blank, X, O}
private int grid;
private State[][] board = new State[grid][grid];
private int moves;


//Default Constructor
public TicTacToe(int grid){

    board = new State[grid][grid];
    moves = 0;
}
public void play(State s, int m, int n){

    if (board[m][n] == State.Blank){
        board[m][n] = s;
    }
    moves++;
}




public boolean hasWon(State[][] board){

    //check winner in rows
    boolean state = false;
    int j = 0;
    int i = 0;
    while(j <= grid) {
        for (i = 0; i <= grid; i++) {
            if (board[j][i] == board[j][i + 1])
                state = true;
            else state = false;
            break;

        }
        if(state == false)
            j++;
        else return true;

    }
    //check winner in columns
    while(j <= grid) {
        for (i = 0; i < grid; i++) {
            if (board[i][j] == board[i + 1][j])
                state = true;
            else state = false;
            break;

        }
        if (state == true)
            j++;
        else return true;
    }
    //check winner in top diagonal
    while(j <= grid && i <= grid){
        if (board[i][j] == board[i+1][j+1])
            state = true;
        else state = false;
        break;

        i++;
        j++;
        return true;
    }


    //check winner in bottom diagonal
    int k = grid;
    int l = grid;
    while(k >= 0 && l >= 0){
        if (board[k][l] == board[k-1][l-1])
            state = true;
        else state = false;
        break;
        k--;
        l--;
        return true;
    }


    return false;
}

}

然而,当在Main类中调用时,程序表现不正常。代码中是否存在逻辑问题。

1 个答案:

答案 0 :(得分:0)

使用

检查行时
for (i = 0; i < n; i++) {
    if (board[j][i] == board[j][i + 1])
        state = true;
}

如果行中的最后两个字符相同,则此代码始终将状态设置为true,与该行中之前的字符无关。

对于列和对角线也是一样的(只有托德所说的才能检查)。

如果找到一些不相等的值,您想要停止比较该行的值:

for (i = 0; i < n; i++) {
    if (board[j][i] == board[j][i + 1]) {
        state = true;
    } else {
        state = false;
        break;
    }
}

行和对角线相同。

编辑: 此外:您没有在构造函数中设置字段网格,因此它始终为0并且您不检查完整的行,列,对角线
丢失:

this.grid = grid;