1

This part of the code is from a school assignment. I got it to work, but I feel like I can simplify it or at least make it look cleaner. However, I have not yet been able to do so. Any suggestions? (It is from a tic tac toe game)

if (board[0][0] == board[0][1] && board[0][1] == board[0][2] && board[0][0] != '-') {
    winner = board[0][0];
} else if (board[1][0] == board[1][1] && board[1][1] == board[1][2] && board[1][0] != '-') {
    winner = board[1][0];
} else if (board[2][0] == board[2][1] && board[2][1] == board[2][2] && board[2][0] != '-') {
    winner = board[2][0];
} else if (board[0][0] == board[1][0] && board[1][0] == board[2][0] && board[0][0] != '-') {
    winner = board[0][0];
} else if (board[0][1] == board[1][1] && board[1][1] == board[2][1] && board[0][1] != '-') {
    winner = board[0][1];
} else if (board[0][2] == board[1][2] && board[1][2] == board[2][2] && board[0][2] != '-') {
    winner = board[0][2];
} else if (board[2][0] == board[1][1] && board[1][1] == board[0][2] && board[2][0] != '-') {
    winner = board[2][0];
} else if (board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[0][0] != '-') {
    winner = board[0][0];
}
khelwood
  • 55,782
  • 14
  • 81
  • 108

3 Answers3

0

try

 if(check(board[0][0],board[0][1],board[0][2]) &&  board[0][2]!='-')
 .....


private boolean check(a,b,c){
    return a==b && b==c;
}

also you can see a better solution here

JavaSheriff
  • 7,074
  • 20
  • 89
  • 159
0

Here is another way of doing it:

int[][] checks = {{0,0,0,1},{1,0,0,1},{2,0,0,1}, // horizontals
                  {0,0,1,0},{0,1,1,0},{0,2,1,0}, // verticals
                  {0,0,1,1},{2,0,-1,1}};         // diagonals
char winner = '-';
for (int[] check : checks)
    if ((winner = checkWinner(board, check[0], check[1], check[2], check[3])) != '-')
        break;
private static char checkWinner(char[][] board, int y, int x, int dy, int dx) {
    char c = board[y][x];
    return (board[y + dy][x + dx] == c && board[y + dy * 2][x + dx * 2] == c ? c : '-');
}
Andreas
  • 154,647
  • 11
  • 152
  • 247
0

What about following approach. As I can see, you have limited number of winners: board[0][0], board[1][0], board[2][0], board[0][1], board[2][0]. You can create separate Predicate for each winnger with appropriate name.

Predicate<char[][]> isZeroOneWinner = new Predicate<char[][]>() {
    @Override
    public boolean test(char[][] board) {
        return board[0][1] == board[1][1] && board[1][1] == board[2][1] && board[0][1] != '-';
    }
};

I think is is better that multiple if...else.

Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35