Mastering Java Swing
Implementing Win Logic - STEP 5
Tic Tac Toe GameNow we’ll add the logic to determine if someone has won the game.
First, we’ll create a method called checkWin to see if a player has achieved 3 X’s or O’s in a row. Here’s the method:
private boolean checkWin() {
int[][] winConditions = {
{0, 1, 2}, {3, 4, 5}, {6, 7, 8}, // Rows
{0, 3, 6}, {1, 4, 7}, {2, 5, 8}, // Columns
{0, 4, 8}, {2, 4, 6} // Diagonals
};
for (int[] condition : winConditions) {
String b1 = buttons[condition[0]].getText();
String b2 = buttons[condition[1]].getText();
String b3 = buttons[condition[2]].getText();
if (!b1.isEmpty() && b1.equals(b2) && b2.equals(b3)) {
return true;
}
}
return false;
}Members only
Keep reading this lesson
You've reached the end of the free preview. Unlock the rest of this lesson plus 27 more lessons in Mastering Java Swing.
- Unlimited coding questions
- Unlimited access to all classroom material
- Weekly live call for questions and guidance
- 3,000 AI tutor tokens / month
- Personal SQL database (3 MB)
- Progress tracking
Cancel any time.