Search⌘ K

Time To Code: Task V and VI

Explore how to implement the core logic for detecting a winner or tie in a Tic-Tac-Toe game using Java. Learn to write methods that check for three consecutive matching marks horizontally, vertically, or diagonally and determine if the game ends in a tie by verifying the game board state.

Finding the winner

Once the players start playing the game, it can end in a win for one player or a tie.

Remember: The win condition is three consecutive "X"s or "O"s horizontally, vertically, or diagonally.

We’ve already provided some code to check for the winner. Before we move to our task, let’s quickly go through the provided code:

Java
char temp = winner(game_board);
if(temp == 'x') {
displayBoard(game_board);
System.out.println("Player1 (x) has won!");
return;
}
else if(temp == 'o') {
displayBoard(game_board);
System.out.println("Player2 (o) has won!");
return;
}
else {
//If it's a tie or not
if(tie(game_board)) {
System.out.println("It's a tie!");
return;
}
else {
//If player1 is true, make it false, and vice versa; this way, the players alternate each turn
p1Turn = !p1Turn;
}
}
  • Line 3: We check if the three consecutive marks are crosses (x). If yes, we declare ...