TicTacToe Java 检查平局

TicTacToe Java check for draw

在我的 TicTacToe 游戏中,我有一个方法可以检查是否有人赢了,这个方法非常有效。但是检查是否有平局的方法不起作用。首先它检查是否有赢家,如果没有,它应该检查是否有平局。一旦场上每 9 个位置进行一次比赛,“平局”的消息就不会出现。我找不到错误。

for (int i = 0; i < 5; i++) {
                System.out.println("welcome!");
                playerMove(gameBoard);
                if (checkIfCurrentPlayerIsWinner(gameBoard, 'X')) {
                    System.out.println("Player won the game!");
                    playerScore++;
                    break;
if (checkDraw(gameBoard)) {
                    System.out.println("It's a draw!");
                    tieScore++;
                    break;
                }
 private static boolean checkDraw(char[][] gameBoard){
        for(int i = 1; i< 10; i++){
            if(getFieldContent(gameBoard, i) != ' '){
                return false;
            }
        }
        return true;
    }
public static char getFieldContent(char[][] gameboard, int fieldNumber) {

        switch (fieldNumber) {
            case 1:
                return gameboard[0][0];
            case 2:
                return gameboard[0][2];
            case 3:
                return gameboard[0][4];
            case 4:
                return gameboard[2][0];
            case 5:
                return gameboard[2][2];
            case 6:
                return gameboard[2][4];
            case 7:
                return gameboard[4][0];
            case 8:
                return gameboard[4][2];
            case 9:
                return gameboard[4][4];
        }
        return ' ';
    }

我在这里推断 gameboard 最初包含所有 space 并且您出于某种原因决定仅将移动存储在其偶数索引中。我还会注意到您的代码缺少一些右括号 (}s)。请以后只编译 post 代码,或者如果编译是你的问题,请指出。

无论如何,checkDraw returns false 如果 gameboard 中的所有测试索引都是 而不是 ' 'true 否则。看起来你想要测试的是相反的,即整个棋盘都已经玩过,即不存在 non-space 单元格。在这种情况下,checkDraw 将类似于以下内容:

private static boolean checkDraw(char[][] gameBoard) {
    for(int i = 1; i < 10; i++) {
        // note that the test is now == instead of !=
        if(getFieldContent(gameBoard, i) == ' ') {
            return false;
        }
    }
    // no non-space cells were found, so the entire board has been
    // played out, resulting in a draw, provided that a separate
    // winner check has already been conducted
    return true;
}