怎样用javafx随机生成迷宫
时间: 2023-07-24 12:04:54 浏览: 53
生成迷宫的常见算法是深度优先搜索(DFS)和广度优先搜索(BFS)。以下是使用DFS算法生成迷宫的JavaFX实现:
1. 创建一个二维数组,表示迷宫的格子。每个格子有四个方向,可以表示为上、下、左、右。
```
int[][] maze = new int[width][height]; // width和height是迷宫的宽度和高度
```
2. 定义一个DFS方法,用于递归生成迷宫。在方法中,随机选择一个未访问的相邻格子,并将其标记为已访问。
```
private void DFS(int x, int y) {
maze[x][y] = VISITED;
List<int[]> neighbors = getUnvisitedNeighbors(x, y); // 获取未访问的相邻格子
while (!neighbors.isEmpty()) {
int[] neighbor = neighbors.remove(random.nextInt(neighbors.size())); // 随机选择一个相邻格子
int nx = neighbor[0], ny = neighbor[1];
if (maze[nx][ny] == UNVISITED) {
removeWall(x, y, nx, ny); // 移除两个格子之间的墙壁
DFS(nx, ny); // 递归访问相邻格子
}
}
}
```
3. 定义一个方法,用于获取未访问的相邻格子。
```
private List<int[]> getUnvisitedNeighbors(int x, int y) {
List<int[]> neighbors = new ArrayList<>();
if (x > 0 && maze[x - 1][y] == UNVISITED) {
neighbors.add(new int[]{x - 1, y}); // 上方格子
}
if (x < width - 1 && maze[x + 1][y] == UNVISITED) {
neighbors.add(new int[]{x + 1, y}); // 下方格子
}
if (y > 0 && maze[x][y - 1] == UNVISITED) {
neighbors.add(new int[]{x, y - 1}); // 左方格子
}
if (y < height - 1 && maze[x][y + 1] == UNVISITED) {
neighbors.add(new int[]{x, y + 1}); // 右方格子
}
return neighbors;
}
```
4. 定义一个方法,用于移除两个格子之间的墙壁。假设每个格子的大小为cellSize,可以通过画线来表示墙壁。
```
private void removeWall(int x1, int y1, int x2, int y2) {
if (x1 == x2) {
int y = y1 < y2 ? y1 : y2;
gc.clearRect(x1 * cellSize, y * cellSize + wallSize, cellSize, wallSize);
} else if (y1 == y2) {
int x = x1 < x2 ? x1 : x2;
gc.clearRect(x * cellSize + wallSize, y1 * cellSize, wallSize, cellSize);
}
}
```
5. 在JavaFX的Application类中,创建一个Canvas和GraphicsContext对象,用于绘制迷宫。然后调用DFS方法生成迷宫。
```
public void start(Stage primaryStage) {
Canvas canvas = new Canvas(width * cellSize + wallSize, height * cellSize + wallSize);
gc = canvas.getGraphicsContext2D();
gc.setFill(Color.WHITE);
gc.fillRect(0, 0, canvas.getWidth(), canvas.getHeight());
gc.setStroke(Color.BLACK);
gc.setLineWidth(wallSize);
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
gc.strokeRect(i * cellSize + wallSize / 2, j * cellSize + wallSize / 2, cellSize, cellSize);
}
}
DFS(0, 0); // 从左上角开始生成迷宫
primaryStage.setScene(new Scene(new StackPane(canvas)));
primaryStage.show();
}
```
完整的代码如下: