99
P13.java
Normal file
99
P13.java
Normal file
@@ -0,0 +1,99 @@
|
||||
import java.applet.*;
|
||||
import java.awt.*;
|
||||
import java.awt.event.*;
|
||||
|
||||
public class P13 extends Applet {
|
||||
private Button[] buttons;
|
||||
private Label statusLabel;
|
||||
private int currentPlayer;
|
||||
|
||||
public void init() {
|
||||
setLayout(new BorderLayout());
|
||||
|
||||
buttons = new Button[9];
|
||||
for (int i = 0; i < 9; i++) {
|
||||
buttons[i] = new Button("");
|
||||
buttons[i].addActionListener(new ButtonClickListener());
|
||||
}
|
||||
|
||||
statusLabel = new Label("Player 1's turn");
|
||||
statusLabel.setAlignment(Label.CENTER);
|
||||
|
||||
Panel buttonPanel = new Panel(new GridLayout(3, 3));
|
||||
for (int i = 0; i < 9; i++) {
|
||||
buttonPanel.add(buttons[i]);
|
||||
}
|
||||
|
||||
add(buttonPanel, BorderLayout.CENTER);
|
||||
add(statusLabel, BorderLayout.SOUTH);
|
||||
currentPlayer = 1;
|
||||
}
|
||||
|
||||
private class ButtonClickListener implements ActionListener {
|
||||
public void actionPerformed(ActionEvent e) {
|
||||
Button clickedButton = (Button) e.getSource();
|
||||
int buttonIndex = -1;
|
||||
|
||||
for (int i = 0; i < 9; i++) {
|
||||
if (buttons[i] == clickedButton) {
|
||||
buttonIndex = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!clickedButton.getLabel().equals("") || isGameOver()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (currentPlayer == 1) {
|
||||
clickedButton.setLabel("X");
|
||||
currentPlayer = 2;
|
||||
statusLabel.setText("Player 2's turn");
|
||||
} else {
|
||||
clickedButton.setLabel("O");
|
||||
currentPlayer = 1;
|
||||
statusLabel.setText("Player 1's turn");
|
||||
}
|
||||
|
||||
if (isGameOver()) {
|
||||
if (currentPlayer == 1) {
|
||||
statusLabel.setText("Player 2 wins!");
|
||||
} else {
|
||||
statusLabel.setText("Player 1 wins!");
|
||||
}
|
||||
} else if (isBoardFull()) {
|
||||
statusLabel.setText("It's a draw!");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isGameOver() {
|
||||
String[] symbols = { "X", "O" };
|
||||
int[][] winCombinations = {
|
||||
{ 0, 1, 2 }, { 3, 4, 5 }, { 6, 7, 8 },
|
||||
{ 0, 3, 6 }, { 1, 4, 7 }, { 2, 5, 8 },
|
||||
{ 0, 4, 8 }, { 2, 4, 6 }
|
||||
};
|
||||
|
||||
for (int[] combination : winCombinations) {
|
||||
String symbol = buttons[combination[0]].getLabel();
|
||||
if (!symbol.equals("") &&
|
||||
symbol.equals(buttons[combination[1]].getLabel()) &&
|
||||
symbol.equals(buttons[combination[2]].getLabel())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean isBoardFull() {
|
||||
for (Button button : buttons) {
|
||||
if (button.getLabel().equals("")) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user