Rafa_Asp1 - 9 months ago 25

Java Question

I have a 3x3 two-dimensional array TicTac toe game, and I am having trouble in a method that should return the winner. The number 1 was assigned to player 1 and -1 to player 2, I need to sum the lines, the columns and the diagonals to see if there is a winner.

`public static int checkWinner (int[][] board) {`

for(int i=0; i<3;i++) {

for(int j=0;j<3;j++) {

if(board[i][j]+ board[i][j]+ board[i][j] == 3) {

return 1;

} else if (board[i][j] + board[i][j] + board[i][j] == -3) {

return -1;

}

}

}

return -10; //placeholder

}

How do I do this, and in a way that is scalable (if I change let's say to a 4x4 grid).

edit: I already saw Algorithm for Determining Tic Tac Toe Game Over, but didn't understand it. That's why I made this question. If anyone can explain what I doing wrong instead of downvoting, I would be very grateful, and would actually learn something instead of copying.

Answer

Assuming that board contains 0's in spaces that haven't been played in yet, and you have a square board, this should work on any size board. I changed your method to return 0 if there was a tie instead of -10. Also note, this is not the most efficient implementation, but it is good. You could add counters and only use one forloop for a runtime of BigTheta(n) but this way is less confusing and BigTheta(n^2) which is any reasonable game of tick-tack-toe (meaning any game a human would ever finish) is more than fast enough.

```
/**
* Checks the board to see if there is a winner
*
* @param board The board to check
* @return Returns (1 if player1 wins) (-1 if player2 wins) and (0 if no one won)
*/
public static int checkWinner (int[][] board) {
int row, col, diagDown=0, diagUp=0;
for(int i=0; i<board[0].length; i++) {
row=0;
col=0;
for(int j=0; j<board.length; j++) {
row+=board[i][j];
col+=board[j][i];
}
//Player1 wins!
if(row==board.length||col==board.length)
return 1;
//Player2 wins!
if(row==-1*board.length||col==-1*board.length)
return -1;
diagDown+=board[i][i];
diagUp+=board[i][board.length-1-i];
}
//Player1 wins!
if(diagUp==board.length||diagDown==board.length)
return 1;
//Player2 wins!
if(diagUp==-1*board.length||diagDown==-1*board.length)
return -1;
//No winner
return 0;
}
```