Search⌘ K

Solution Review: Task V and VI

Explore how to implement the core logic for a Tic-Tac-Toe game by coding the winning conditions using loops and if statements, and learn how to check for a tie by examining all board positions. This lesson helps you understand key programming concepts in Java through hands-on application in a real project.

Task V: Implement the winning conditions

The task was to code the winning conditions to check for the winner.

Java
public static char winner(char[][] game_board) {
//Check all the rows
for(int i = 0; i < 3; i++) {
if(game_board[i][0] == game_board[i][1] && game_board[i][1] == game_board[i][2] && game_board[i][0] != ' ') {
return game_board[i][0];
}
}
//Check each column
for(int j = 0; j < 3; j++) {
if(game_board[0][j] == game_board[1][j] && game_board[1][j] == game_board[2][j] && game_board[0][j] != ' ') {
return game_board[0][j];
}
}
//Check the diagonals
if(game_board[0][0] == game_board[1][1] && game_board[1][1] == game_board[2][2] && game_board[0][0] != ' ') {
return game_board[0][0];
}
if(game_board[2][0] == game_board[1][1] && game_board[1][1] == game_board[0][2] && game_board[2][0] != ' ') {
return game_board[2][0];
}
//Nobody has not won yet
return ' ';
}
  • Lines 4–8: We use a for loop to check if there are any three consecutive x or o in any of our rows. We keep the column values (the second bracket) constant and iterate over the rows.

  • Lines 10–14: We use a ...