Home > other >  TicTacToe Java check for draw
TicTacToe Java check for draw

Time:10-06

In my TicTacToe game I have a method which checks if someone wins and this works perfectly. But the methode for checking if there is a draw doesn't work. At first it checks if there is a winner and when not it should check if there's a draw. As soon as every 9 places are played in the field the message "it's draw" doesn't appear. I can't find the mistake.

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 ' ';
    }

CodePudding user response:

I'm inferring here that gameboard initially contains all spaces and that you've for some reason decided to only store moves in its even indices. I'll note also that your code is missing some closing braces (}s). Please in the future only post code that compiles, or if compilation is your problem, indicate such.

In any event, checkDraw returns false if all of the tested indices in gameboard are not ' ' and true otherwise. It seems like what you want to test for is the opposite, i.e. that the entire board has been played on, i.e. no non-space cells exist. That being the case, checkDraw would look something like the following:

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;
}
  • Related