673
Here is a simple implementation of a classic Tic-Tac-Toe game in Java using Swing.
This code sets up a 3×3 grid of buttons, allowing two players (Player X and Player O) to take turns placing their marks in an attempt to win the game.
Code
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TicTacToe extends JFrame implements ActionListener {
private JButton[] buttons = new JButton[9];
private boolean xTurn = true;
public TicTacToe() {
// Set up the frame
setTitle("Tic-Tac-Toe");
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(3, 3));
// Initialize buttons for the grid
for (int i = 0; i < 9; i++) {
buttons[i] = new JButton("");
buttons[i].setFont(new Font("Arial", Font.PLAIN, 60));
buttons[i].setFocusPainted(false);
buttons[i].addActionListener(this);
add(buttons[i]);
}
}
@Override
public void actionPerformed(ActionEvent e) {
JButton clickedButton = (JButton) e.getSource();
// If the button is already marked, do nothing
if (!clickedButton.getText().equals("")) {
return;
}
// Set the text to "X" or "O" depending on whose turn it is
if (xTurn) {
clickedButton.setText("X");
} else {
clickedButton.setText("O");
}
// Check for a win or a draw
if (checkForWin()) {
JOptionPane.showMessageDialog(this, (xTurn ? "X" : "O") + " wins!");
resetGame();
} else if (checkForDraw()) {
JOptionPane.showMessageDialog(this, "It's a draw!");
resetGame();
}
// Toggle the turn
xTurn = !xTurn;
}
private boolean checkForWin() {
// Winning combinations
int[][] winningCombinations = {
{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
};
// Check each winning combination
for (int[] combo : winningCombinations) {
String b1 = buttons[combo[0]].getText();
String b2 = buttons[combo[1]].getText();
String b3 = buttons[combo[2]].getText();
if (!b1.equals("") && b1.equals(b2) && b2.equals(b3)) {
return true;
}
}
return false;
}
private boolean checkForDraw() {
// Check if all buttons are filled
for (JButton button : buttons) {
if (button.getText().equals("")) {
return false;
}
}
return true;
}
private void resetGame() {
// Clear all buttons and reset the turn to X
for (JButton button : buttons) {
button.setText("");
}
xTurn = true;
}
public static void main(String[] args) {
// Create and display the game window
SwingUtilities.invokeLater(() -> {
TicTacToe game = new TicTacToe();
game.setVisible(true);
});
}
}
Explanation of the Code
- Class Setup:
- The TicTacToe class extends JFrame, making it a window with GUI elements.
- Implements ActionListener to handle button click events.
- Fields:
- buttons: An array of JButton objects representing each cell in the 3×3 grid.
- xTurn: A boolean that tracks whether it is Player X’s turn (true) or Player O’s turn (false).
- Constructor TicTacToe():
- Sets up the main game window with the title “Tic-Tac-Toe”, size 400×400 pixels, and a 3×3 grid layout.
- Initializes each button in the grid with:
- Large font size for visibility.
- Action listeners so each button can respond to clicks.
- Adds each button to the JFrame’s grid layout.
- Action Handling (actionPerformed):
- Determines which button was clicked and updates it with “X” or “O”, depending on the current player.
- Calls checkForWin() to see if the current move resulted in a win.
- If a win is detected, displays a message box declaring the winner and calls resetGame() to start a new game.
- Calls checkForDraw() to check if the board is full without any winning combination, indicating a draw.
- If a draw is detected, displays a message and resets the game.
- Toggles xTurn to switch to the other player.
- Win Checking (checkForWin()):
- Defines the possible winning combinations in the winningCombinations array.
- Iterates over each combination and checks if three buttons in a row contain the same mark (“X” or “O”).
- If a winning combination is found, returns true.
- Draw Checking (checkForDraw()):
- Checks if all buttons have non-empty text (meaning the board is full) and returns true if no empty spots remain.
- Reset Game (resetGame()):
- Clears all button text and resets xTurn to true so Player X always starts first in a new game.
- Main Method (main):
- Creates and shows the TicTacToe game window using SwingUtilities.invokeLater to ensure thread safety.
Running the Code
To run this code:
- Save the file as TicTacToe.java.
- Compile and run the program:
javac TicTacToe.java java TicTacToe
