可以帮我写个例子吗
时间: 2023-10-10 22:09:31 浏览: 60
my example
当然可以,以下是一个简单的 Java 代码示例,用于生成一个 10 行 10 列的迷宫,并在控制台中输出迷宫:
```java
import java.util.Random;
public class MazeGenerator {
private int[][] maze;
private int rows;
private int cols;
private int startRow;
private int startCol;
private int endRow;
private int endCol;
public MazeGenerator(int rows, int cols) {
this.rows = rows;
this.cols = cols;
maze = new int[rows][cols];
generateMaze();
setStartAndEnd();
}
private void generateMaze() {
Random rand = new Random();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
maze[i][j] = rand.nextInt(2);
}
}
}
private void setStartAndEnd() {
startRow = 0;
startCol = 0;
endRow = rows - 1;
endCol = cols - 1;
maze[startRow][startCol] = 0;
maze[endRow][endCol] = 0;
}
public void printMaze() {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (maze[i][j] == 1) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
public static void main(String[] args) {
MazeGenerator maze = new MazeGenerator(10, 10);
maze.printMaze();
}
}
```
该代码使用了随机数生成算法,生成了一个包含随机障碍物的迷宫,并在控制台中输出了迷宫。您可以自行修改代码来增加起点和终点位置,并将其转化为图形界面。
阅读全文