缘起:
去年(大三上学期)比较喜欢写小游戏,于是想试着写个迷宫试一下。
程序效果:
按下空格显示路径:
思考过程:
迷宫由一个一个格子组成,要求从入口到出口只有一条路径.
想了一下各种数据结构,似乎树是比较合适的,从根节点到每一个子节点都只有一条路径。假设入口是根节点,出口是树中某个子节点,那么,从根节点到该子节点的路径肯定是唯一的。
所以如果能构造一棵树把所有的格子都覆盖到,也就能够做出一个迷宫了。
另外还要求树的父节点和子节点必须是界面上相邻的格子。
在界面显示时,父节点和子节点之间共用的边不画,其他的边都画出来,就能画出一个迷宫。
之后就是想一下该怎么实现这样一棵树。
首要的两个问题:
1、树怎么表示?
2、怎么构造这棵树?
1.树怎么表示?
假设像写二叉树一样实现这棵树,那么每个树节点里就要存储一个坐标(X,Y)表示一个格子,另外还要存储四个指针。指针中有的为空,有的不为空,不为空的指针指向子节点,子节点保存邻居格子的坐标。这样做最大的问题是无法判定是否所有的格子都在树中。也许还要用一个二维数组作标志数组。
假如用二维数组表示迷宫的格子。每个数组元素存储一个指向父节点的引用,这样也可以形成一个虚拟的树。于是就用一个N*N的二维数组,表示N*N个格子,每个数组元素(Lattice)中有一个指向父节点的引用(father)。另外,为了能方便的获取格子的坐标,还要保存坐标信息。
2.怎么构造这棵树?
首先选定一个格子作为根节点。为了让迷宫的形状够随机,我选择随机生成一个坐标作为根节点。其实,选择确定的一个坐标也可以。
然后,怎样往这棵树上增加节点呢?
在这里我走了不少弯路,一开始想的是一种现在看来类似回溯的算法(当时还不知道回溯算法。。),但是时间复杂度很高,大概当迷宫为64*64的时候,算法就不出结果了。
然后,又使用了一种扫深度搜索也是回溯描的方法,每次扫描在当前树中找一个节点,看它的邻居格子是否在树中,如果还没在树中,就将该邻居格子加入树中,如果已在树中,就看下一个邻居格子,如果该节点所有邻居格子都在树中了,就找下一个节点,继续同样的操作。另外为了让迷宫生成的随机,扫描的起始位置是随机的就可以了。但是,该方法生成的迷宫中的路径总是不够深,没有我想要的曲折深入的效果。毕竟是类似广度搜索的方法。而且,这样做总还像是靠蛮力,算法不够聪明简洁。
最后,我终于想到使用深度搜索。。大概是因为数据结构已经学过了一年,又没太练,忘了不少,所以一直没想到这个应该第一想到的方法。。
随机选择一个格子作为根节点,从它开始随机地深度搜索前进,开出一条路来,直到无路可走了,退回一步,换另一条路,再走到无路可走,回退一步,换另一条……如此循环往复,直到完全无路可走。。。其实也还是回溯。
在程序里就是以下过程(详见代码中的createMaze()函数):
随机选择一个格子作为根节点,将它压进栈里。
然后在栈不为空的时候执行以下循环:
取出一个格子,将它的INTREE标志设置为1,然后将它的所有不在树中的邻居格子压进栈里(顺序随机),并且让这些邻居格子的father指向该格子。
解决了这两个问题,其余的画迷宫、显示路径、小球移动也就比较简单了。
代码:
1 package maze; 2 3 import java.awt.Color; 4 import java.awt.Graphics; 5 import java.awt.event.KeyAdapter; 6 import java.awt.event.KeyEvent; 7 import java.util.Random; 8 import java.util.Stack; 9 import javax.swing.JFrame; 10 import javax.swing.JOptionPane; 11 import javax.swing.JPanel; 12 class Lattice { 13 static final int INTREE = 1; 14 static final int NOTINTREE = 0; 15 private int x = -1; 16 private int y = -1; 17 private int flag = NOTINTREE; 18 private Lattice father = null; 19 public Lattice(int xx, int yy) { 20 x = xx; 21 y = yy; 22 } 23 public int getX() { 24 return x; 25 } 26 public int getY() { 27 return y; 28 } 29 public int getFlag() { 30 return flag; 31 } 32 public Lattice getFather() { 33 return father; 34 } 35 public void setFather(Lattice f) { 36 father = f; 37 } 38 public void setFlag(int f) { 39 flag = f; 40 } 41 public String toString() { 42 return new String("(" + x + "," + y + ")\n"); 43 } 44 } 45 public class Maze extends JPanel { 46 private static final long serialVersionUID = -8300339045454852626L; 47 private int NUM, width, padding;// width 每个格子的宽度和高度 48 private Lattice[][] maze; 49 private int ballX, ballY; 50 private boolean drawPath = false; 51 Maze(int m, int wi, int p) { 52 NUM = m; 53 width = wi; 54 padding = p; 55 maze = new Lattice[NUM][NUM]; 56 for (int i = 0; i <= NUM - 1; i++) 57 for (int j = 0; j <= NUM - 1; j++) 58 maze[i][j] = new Lattice(i, j); 59 createMaze(); 60 setKeyListener(); 61 this.setFocusable(true); 62 } 63 private void init() { 64 for (int i = 0; i <= NUM - 1; i++) 65 for (int j = 0; j <= NUM - 1; j++) { 66 maze[i][j].setFather(null); 67 maze[i][j].setFlag(Lattice.NOTINTREE); 68 } 69 ballX = 0; 70 ballY = 0; 71 drawPath = false; 72 createMaze(); 73 // setKeyListener(); 74 this.setFocusable(true); 75 repaint(); 76 } 77 public int getCenterX(int x) { 78 return padding + x * width + width / 2; 79 } 80 public int getCenterY(int y) { 81 return padding + y * width + width / 2; 82 } 83 84 public int getCenterX(Lattice p) { 85 return padding + p.getY() * width + width / 2; 86 } 87 public int getCenterY(Lattice p) { 88 return padding + p.getX() * width + width / 2; 89 } 90 private void checkIsWin() { 91 if (ballX == NUM - 1 && ballY == NUM - 1) { 92 JOptionPane.showMessageDialog(null, "YOU WIN !", "你走出了迷宫。", 93 JOptionPane.PLAIN_MESSAGE); 94 init(); 95 } 96 } 97 synchronized private void move(int c) { 98 int tx = ballX, ty = ballY; 99 // System.out.println(c); 100 switch (c) { 101 case KeyEvent.VK_LEFT : 102 ty--; 103 break; 104 case KeyEvent.VK_RIGHT : 105 ty++; 106 break; 107 case KeyEvent.VK_UP : 108 tx--; 109 break; 110 case KeyEvent.VK_DOWN : 111 tx++; 112 break; 113 case KeyEvent.VK_SPACE : 114 if (drawPath == true) { 115 drawPath = false; 116 } else { 117 drawPath = true; 118 } 119 break; 120 default : 121 } 122 if (!isOutOfBorder(tx, ty) 123 && (maze[tx][ty].getFather() == maze[ballX][ballY] 124 || maze[ballX][ballY].getFather() == maze[tx][ty])) { 125 ballX = tx; 126 ballY = ty; 127 } 128 } 129 private void setKeyListener() { 130 this.addKeyListener(new KeyAdapter() { 131 public void keyPressed(KeyEvent e) { 132 int c = e.getKeyCode(); 133 move(c); 134 repaint(); 135 checkIsWin(); 136 137 } 138 }); 139 } 140 private boolean isOutOfBorder(Lattice p) { 141 return isOutOfBorder(p.getX(), p.getY()); 142 } 143 private boolean isOutOfBorder(int x, int y) { 144 return (x > NUM - 1 || y > NUM - 1 || x < 0 || y < 0) ? true : false; 145 } 146 private Lattice[] getNeis(Lattice p) { 147 final int[] adds = {-1, 0, 1, 0, -1};// 顺序为上右下左 148 if (isOutOfBorder(p)) { 149 return null; 150 } 151 Lattice[] ps = new Lattice[4];// 顺序为上右下左 152 int xt; 153 int yt; 154 for (int i = 0; i <= 3; i++) { 155 xt = p.getX() + adds[i]; 156 yt = p.getY() + adds[i + 1]; 157 if (isOutOfBorder(xt, yt)) 158 continue; 159 ps[i] = maze[xt][yt]; 160 } 161 return ps; 162 } 163 private void createMaze() { 164 Random random = new Random(); 165 int rx = Math.abs(random.nextInt()) % NUM; 166 int ry = Math.abs(random.nextInt()) % NUM; 167 Stack<Lattice> s = new Stack<Lattice>(); 168 Lattice p = maze[rx][ry]; 169 Lattice neis[] = null; 170 s.push(p); 171 while (!s.isEmpty()) { 172 p = s.pop(); 173 p.setFlag(Lattice.INTREE); 174 neis = getNeis(p); 175 int ran = Math.abs(random.nextInt()) % 4; 176 for (int a = 0; a <= 3; a++) { 177 ran++; 178 ran %= 4; 179 if (neis[ran] == null || neis[ran].getFlag() == Lattice.INTREE) 180 continue; 181 s.push(neis[ran]); 182 neis[ran].setFather(p); 183 } 184 } 185 // changeFather(maze[0][0],null); 186 } 187 private void changeFather(Lattice p, Lattice f) { 188 if (p.getFather() == null) { 189 p.setFather(f); 190 return; 191 } else { 192 changeFather(p.getFather(), p); 193 } 194 } 195 private void clearFence(int i, int j, int fx, int fy, Graphics g) { 196 int sx = padding + ((j > fy ? j : fy) * width), 197 sy = padding + ((i > fx ? i : fx) * width), 198 dx = (i == fx ? sx : sx + width), 199 dy = (i == fx ? sy + width : sy); 200 if (sx != dx) { 201 sx++; 202 dx--; 203 } else { 204 sy++; 205 dy--; 206 } 207 g.drawLine(sx, sy, dx, dy); 208 } 209 protected void paintComponent(Graphics g) { 210 super.paintComponent(g); 211 for (int i = 0; i <= NUM; i++) { 212 g.drawLine(padding + i * width, padding, padding + i * width, 213 padding + NUM * width); 214 } 215 for (int j = 0; j <= NUM; j++) { 216 g.drawLine(padding, padding + j * width, padding + NUM * width, 217 padding + j * width); 218 } 219 g.setColor(this.getBackground()); 220 for (int i = NUM - 1; i >= 0; i--) { 221 for (int j = NUM - 1; j >= 0; j--) { 222 Lattice f = maze[i][j].getFather(); 223 if (f != null) { 224 int fx = f.getX(), fy = f.getY(); 225 clearFence(i, j, fx, fy, g); 226 } 227 } 228 } 229 g.drawLine(padding, padding + 1, padding, padding + width - 1); 230 int last = padding + NUM * width; 231 g.drawLine(last, last - 1, last, last - width + 1); 232 g.setColor(Color.RED); 233 g.fillOval(getCenterX(ballY) - width / 3, getCenterY(ballX) - width / 3, 234 width / 2, width / 2); 235 if (drawPath == true) 236 drawPath(g); 237 } 238 private void drawPath(Graphics g) { 239 Color PATH_COLOR = Color.ORANGE, BOTH_PATH_COLOR = Color.PINK; 240 if (drawPath == true) 241 g.setColor(PATH_COLOR); 242 else 243 g.setColor(this.getBackground()); 244 Lattice p = maze[NUM - 1][NUM - 1]; 245 while (p.getFather() != null) { 246 p.setFlag(2); 247 p = p.getFather(); 248 } 249 g.fillOval(getCenterX(p) - width / 3, getCenterY(p) - width / 3, 250 width / 2, width / 2); 251 p = maze[0][0]; 252 while (p.getFather() != null) { 253 if (p.getFlag() == 2) { 254 p.setFlag(3); 255 g.setColor(BOTH_PATH_COLOR); 256 } 257 g.drawLine(getCenterX(p), getCenterY(p), getCenterX(p.getFather()), 258 getCenterY(p.getFather())); 259 p = p.getFather(); 260 } 261 g.setColor(PATH_COLOR); 262 p = maze[NUM - 1][NUM - 1]; 263 while (p.getFather() != null) { 264 if (p.getFlag() == 3) 265 break; 266 g.drawLine(getCenterX(p), getCenterY(p), getCenterX(p.getFather()), 267 getCenterY(p.getFather())); 268 p = p.getFather(); 269 } 270 } 271 public static void main(String[] args) { 272 final int n = 30, width = 600, padding = 20, LX = 200, LY = 100; 273 JPanel p = new Maze(n, (width - padding - padding) / n, padding); 274 JFrame frame = new JFrame("MAZE(按空格键显示或隐藏路径)"); 275 frame.getContentPane().add(p); 276 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 277 frame.setSize(width + padding, width + padding + padding); 278 frame.setLocation(LX, LY); 279 frame.setVisible(true); 280 } 281 }
程序完成于大三上学期。
随笔写于2016.5.8