使用javafx自动生成一个迷宫代码
时间: 2023-07-03 13:24:13 浏览: 115
Spring-generator是基于javafx8开发的图形界面Spring代码生成器
好的,以下是使用JavaFX自动生成迷宫的示例代码:
```java
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.layout.BorderPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import java.util.Random;
public class MazeGenerator extends Application {
// 迷宫参数
private static final int MAZE_WIDTH = 50;
private static final int MAZE_HEIGHT = 50;
private static final int CELL_SIZE = 10;
// 迷宫地图
private int[][] maze;
// JavaFX界面
private Canvas canvas;
// 随机数生成器
private Random random = new Random();
@Override
public void start(Stage primaryStage) throws Exception {
BorderPane root = new BorderPane();
// 创建Canvas
canvas = new Canvas(MAZE_WIDTH * CELL_SIZE, MAZE_HEIGHT * CELL_SIZE);
root.setCenter(canvas);
// 生成迷宫
generateMaze();
// 绘制迷宫
drawMaze();
// 创建场景
Scene scene = new Scene(root, MAZE_WIDTH * CELL_SIZE, MAZE_HEIGHT * CELL_SIZE);
// 设置舞台
primaryStage.setTitle("Maze Generator");
primaryStage.setScene(scene);
primaryStage.show();
}
// 生成迷宫
private void generateMaze() {
// 初始化迷宫地图
maze = new int[MAZE_HEIGHT][MAZE_WIDTH];
for (int i = 0; i < MAZE_HEIGHT; i++) {
for (int j = 0; j < MAZE_WIDTH; j++) {
maze[i][j] = 1;
}
}
// 随机生成起点和终点
int startX = random.nextInt(MAZE_WIDTH);
int startY = random.nextInt(MAZE_HEIGHT);
int endX = random.nextInt(MAZE_WIDTH);
int endY = random.nextInt(MAZE_HEIGHT);
// 生成迷宫地图
maze[startY][startX] = 0;
maze[endY][endX] = 0;
generateMazeRecursive(startX, startY, endX, endY);
}
// 递归生成迷宫
private void generateMazeRecursive(int x, int y, int endX, int endY) {
// 生成方向数组
int[][] directions = {
{ 1, 0 },
{ -1, 0 },
{ 0, 1 },
{ 0, -1 }
};
// 随机打乱方向数组
for (int i = 0; i < directions.length; i++) {
int j = random.nextInt(directions.length);
int[] temp = directions[i];
directions[i] = directions[j];
directions[j] = temp;
}
// 遍历方向数组
for (int i = 0; i < directions.length; i++) {
int newX = x + directions[i][0] * 2;
int newY = y + directions[i][1] * 2;
if (newX >= 0 && newX < MAZE_WIDTH && newY >= 0 && newY < MAZE_HEIGHT) {
if (maze[newY][newX] == 1) {
// 打通墙壁
maze[y + directions[i][1]][x + directions[i][0]] = 0;
maze[newY][newX] = 0;
// 递归生成迷宫
generateMazeRecursive(newX, newY, endX, endY);
}
}
}
}
// 绘制迷宫
private void drawMaze() {
GraphicsContext gc = canvas.getGraphicsContext2D();
// 绘制背景
gc.setFill(Color.WHITE);
gc.fillRect(0, 0, canvas.getWidth(), canvas.getHeight());
// 绘制迷宫
for (int i = 0; i < MAZE_HEIGHT; i++) {
for (int j = 0; j < MAZE_WIDTH; j++) {
if (maze[i][j] == 1) {
gc.setFill(Color.BLACK);
gc.fillRect(j * CELL_SIZE, i * CELL_SIZE, CELL_SIZE, CELL_SIZE);
}
}
}
}
public static void main(String[] args) {
launch(args);
}
}
```
这个示例程序使用随机Prim算法生成迷宫,然后使用JavaFX绘制迷宫界面。您可以根据需要对代码进行修改和优化。
阅读全文