迷宫开发
文章目录
前言
该文章为记录迷宫具体实现程序以及相关思考
一、深度优先遍历创建迷宫
创建二维数组并完成初始化`
1.生成迷宫所需要的变量
public class MyMaze extends JPanel implements KeyListener {
//生成地图用到变量
final static int wall =0; //代表墙
final static int road =1; //代表空地
static int num = 21; //迷宫长度
int width = 20; //迷宫宽度
static int [][] mMap; //迷宫
boolean[][] visit; //用来标记某一格是否被访问过
Node start = new Node(1,1); //开始节点
Node end = new Node(num-2,num-2);//结束节点
Node cur; //当前格
Node next; //下一格
Stack<Node> path = new Stack<>();//记录生成地图时遍历的顺序
//走迷宫时用到的变量
private Node movePerson;
List<Integer> xPath=new ArrayList<>();//记录迷宫中行进的轨迹
List<Integer> yPath=new ArrayList<>();
private boolean drawPath = false;
2.初始化迷宫
MyMaze(){
mMap = new int [num][num];
visit = new boolean[num][num];
for (int i = 0; i < num; i = i+2) {//初始化地图的空格
for (int j = 0; j < num; j=j+2){
mMap[i][j] = wall;//其余均为墙
visit[i][j] = false;
}
}
for (int i = 1; i < num; i = i+2) {//初始化地图的空格
for (int j = 1; j < num; j=j+2){
mMap[i][j] = road;//奇数行奇数列的格子均为路
visit[i][j] = false;
}
}
visit[start.x][start.y] = true;
mMap[start.x][start.y] = road;
cur = start; //将当前格标记为开始格
movePerson=new Node(start.x-1,start.y);
drawPath=false;
createMaze();
this.addKeyListener(this);
this.setFocusable(true);
}
public void init(){//第一轮结束后,再次初始化地图
mMap = new int [num][num];
visit = new boolean[num][num]