import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
private boolean playerXTurn = true;
private int[][] board;
public Main() {
super("Tic Tac Toe");
setDefaultCloseOperation
(JFrame.
EXIT_ON_CLOSE); setSize(300, 300);
setLocationRelativeTo(null);
// Create the board
board = new int[3][3];
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 3; col++) {
buttons
[row
][col
] = new JButton(""); buttons
[row
][col
].
setFont(new Font("Arial",
Font.
BOLD,
40)); buttons[row][col].addActionListener(this);
boardPanel.add(buttons[row][col]);
}
}
// Create the status label
statusLabel
= new JLabel("X's turn");
setVisible(true);
}
@Override
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 3; col++) {
if (e.getSource() == buttons[row][col]) {
if (board[row][col] == 0) {
if (playerXTurn) {
buttons[row][col].setText("X");
board[row][col] = 1; // X
} else {
buttons[row][col].setText("O");
board[row][col] = -1; // O
}
playerXTurn = !playerXTurn;
if (playerXTurn) {
statusLabel.setText("X's turn");
} else {
statusLabel.setText("O's turn");
}
if (checkWin()) {
if (playerXTurn) {
statusLabel.setText("O wins!");
} else {
statusLabel.setText("X wins!");
}
disableButtons();
} else if (checkDraw()) {
statusLabel.setText("It's a draw!");
disableButtons();
}
}
}
}
}
}
private boolean checkWin() {
// Check rows
for (int row = 0; row < 3; row++) {
if (board[row][0] != 0 && board[row][0] == board[row][1] && board[row][0] == board[row][2]) {
return true;
}
}
// Check columns
for (int col = 0; col < 3; col++) {
if (board[0][col] != 0 && board[0][col] == board[1][col] && board[0][col] == board[2][col]) {
return true;
}
}
// Check diagonals
if (board[0][0] != 0 && board[0][0] == board[1][1] && board[0][0] == board[2][2]) {
return true;
}
if (board[0][2] != 0 && board[0][2] == board[1][1] && board[0][2] == board[2][0]) {
return true;
}
return false;
}
private boolean checkDraw() {
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 3; col++) {
if (board[row][col] == 0) {
return false; // There are still empty cells
}
}
}
return true; // All cells are filled
}
private void disableButtons() {
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 3; col++) {
buttons[row][col].setEnabled(false);
}
}
}
public static void main
(String[] args
) { public void run() {
new Main();
}
});
}
}