井字游戏Java中的获胜条件

时间:2019-11-19 14:08:01

标签: java tic-tac-toe

嘿,我做了井字游戏(哦,我们再来一次... :)),但是我的获胜条件有问题,无论我选择什么, isGameOver 方法都返回true,我无法确定搞清楚为什么。有小费吗?我以为它会将空格作为相同的字符进行比较,但是我不确定...

public class zadanie16 {
public static char[][] board = new char[3][3];
public static Scanner scanner = new Scanner(System.in);
public static int row, column;
public static char turn = 'x';

public static void main(String[] args) {
    initializeBoard();
    play();
}

public static char[][] initializeBoard() {
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            board[i][j] = ' ';
        }

    }
    return board;
}

public static void printBoard() {
    System.out.println("/---|---|---\\");
    System.out.println("| " + board[0][0] + " | " + board[0][1] + " | " + board[0][2] + " |");
    System.out.println("|-----------|");
    System.out.println("| " + board[1][0] + " | " + board[1][1] + " | " + board[1][2] + " |");
    System.out.println("|-----------|");
    System.out.println("| " + board[2][0] + " | " + board[2][1] + " | " + board[2][2] + " |");
    System.out.println("/---|---|---\\");
}

public static void play() {
    boolean isPlaying = true;
    while (isPlaying) {
        System.out.println("Podaj wiersz");
        row = scanner.nextInt() - 1;
        System.out.println("Podaj kolumne");
        column = scanner.nextInt() - 1;
        board[row][column] = turn;
        if (isGameOver(row, column)) {
            isPlaying = false;
            System.out.println("Gratulations player" + turn + " wins!");
        }

        printBoard();
        if (turn == 'x') {
            turn = 'o';
        } else {
            turn = 'x';
        }
    }
}

public static boolean isGameOver(int rowMove, int columnMove) {
    if (board[0][columnMove] == board[0][columnMove] && board[0][columnMove] == board[0][columnMove]) {
        return true;
    }
    if (board[rowMove][0] == board[rowMove][0] && board[rowMove][0] == board[rowMove][2]) {
        return true;
    }


    return false;
}

}

0 个答案:

没有答案