记忆力测试游戏javafx
时间: 2023-07-04 14:09:55 浏览: 131
好的,下面是一个简单的记忆力测试游戏的JavaFX代码示例:
```java
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;
import javafx.scene.text.Font;
import javafx.stage.Stage;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class MemoryGame extends Application {
private static final int GRID_SIZE = 4;
private static final int NUM_BUTTONS = GRID_SIZE * GRID_SIZE;
private static final int MAX_NUMBER = 99;
private static final int BUTTON_SIZE = 80;
private List<Integer> numbers = new ArrayList<>();
private int currentNumber = 1;
@Override
public void start(Stage primaryStage) {
// Initialize the numbers list with random numbers
for (int i = 1; i <= NUM_BUTTONS / 2; i++) {
numbers.add(i);
numbers.add(i);
}
Collections.shuffle(numbers);
// Create the GridPane layout
GridPane gridPane = new GridPane();
gridPane.setAlignment(Pos.CENTER);
gridPane.setHgap(10);
gridPane.setVgap(10);
// Add the buttons to the GridPane
for (int i = 0; i < GRID_SIZE; i++) {
for (int j = 0; j < GRID_SIZE; j++) {
Button button = new Button("?");
button.setPrefSize(BUTTON_SIZE, BUTTON_SIZE);
button.setFont(Font.font(24));
final int index = i * GRID_SIZE + j;
button.setOnAction(event -> {
if (button.getText().equals("?")) {
button.setText(Integer.toString(numbers.get(index)));
if (currentNumber == numbers.get(index)) {
currentNumber++;
if (currentNumber == NUM_BUTTONS / 2 + 1) {
// Game over
Button restartButton = new Button("Restart");
restartButton.setPrefSize(BUTTON_SIZE * GRID_SIZE, BUTTON_SIZE);
restartButton.setFont(Font.font(24));
restartButton.setOnAction(event1 -> {
// Restart the game
Collections.shuffle(numbers);
for (int k = 0; k < NUM_BUTTONS; k++) {
Button b = (Button) gridPane.getChildren().get(k);
b.setText("?");
}
currentNumber = 1;
gridPane.getChildren().remove(restartButton);
});
gridPane.add(restartButton, 0, GRID_SIZE);
}
}
}
});
gridPane.add(button, j, i);
}
}
Scene scene = new Scene(gridPane, BUTTON_SIZE * GRID_SIZE, BUTTON_SIZE * GRID_SIZE);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
```
这个游戏的规则很简单:玩家需要在一个 $4\times4$ 的网格中找到所有数字,数字从 $1$ 到 $8$,但是它们是随机排列的。每当玩家点击一个按钮时,它将显示该按钮下面的数字。如果该数字与当前数字匹配,玩家将继续找下一个数字。当玩家找到所有数字时,游戏结束并显示一个重新开始游戏的按钮。
这个游戏的实现中使用了JavaFX的GridPane布局来创建网格,按钮的大小为80x80,字体大小为24。在初始化时,数字列表被填充了从1到8的数字,并随机打乱了顺序。当玩家点击一个按钮时,它将检查该按钮下面的数字是否与当前数字匹配,如果是,则当前数字将增加1。当当前数字达到最大值时,游戏结束并显示重新开始游戏的按钮。
阅读全文