Newer
Older
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
public class TicTacToeFX extends Application {
private Button[][] buttons = new Button[3][3];
private boolean isXTurn = true;
GridPane grid = new GridPane();
// 3x3 Buttons hinzufügen
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 3; col++) {
Button button = new Button();
button.setPrefSize(100, 100); // Größe der Buttons
grid.add(button, col, row); // Hinzufügen zum Grid
buttons[row][col] = button;
button.setOnAction(event -> handleButtonClick(button));
Scene scene1 = new Scene(grid, 300, 300); // Größe der Szene
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
private void handleButtonClick(Button button) {
if(button.getText().isEmpty()) {
if (this.isXTurn) {
button.setText("X");
this.isXTurn = false;
} else {
button.setText("O");
this.isXTurn = true;
}
if (checkForWin()) {
buttons[1][1].setText("juhu");
}
else if(checkForDraw()){
buttons[1][1].setText("draw");
}
}
}
private boolean checkForWin(){
for(int row = 0; row < 3; row++){
String text1 = buttons[row][0].getText();
String text2 = buttons[row][1].getText();
String text3 = buttons[row][2].getText();
if(!text1.isEmpty() && text1.equals(text2) && text1.equals(text3)){
return true;
}
}
for(int col = 0; col < 3; col++){
String text1 = buttons[0][col].getText();
String text2 = buttons[1][col].getText();
String text3 = buttons[2][col].getText();
if(!text1.isEmpty() && text1.equals(text2) && text1.equals(text3)){
return true;
}
}
String upperLeftCorner = buttons[0][0].getText();
String center = buttons[1][1].getText();
String lowerRightCorner = buttons[2][2].getText();
String upperRightCorner = buttons[0][2].getText();
String lowerLeftCorner = buttons[2][0].getText();
if(!upperLeftCorner.isEmpty() && upperLeftCorner.equals(center) && upperLeftCorner.equals(lowerRightCorner)){
return true;
}
if(!upperRightCorner.isEmpty() && upperRightCorner.equals(center) && upperRightCorner.equals(lowerLeftCorner)){
return true;
}
return false;
}
private boolean checkForDraw(){
for(int row = 0; row < 3; row++){
for(int col = 0; col < 3; col++){
if(buttons[row][col].getText().isEmpty()){
return false;
}
}
}
return true;
}
public static void main(String[] args) {
launch(args);
}
}