Java迷宫游戏
缘起:
去年(大三上学期)比较喜欢写小游戏,于是想试着写个迷宫试一下。
程序效果:
按下空格显示路径:
思考过程:
迷宫由一个一个格子组成,要求从入口到出口只有一条路径.
想了一下各种数据结构,似乎树是比较合适的,从根节点到每一个子节点都只有一条路径。假设入口是根节点,出口是树中某个子节点,那么,从根节点到该子节点的路径肯定是唯一的。
所以如果能构造一棵树把所有的格子都覆盖到,也就能够做出一个迷宫了。
另外还要求树的父节点和子节点必须是界面上相邻的格子。
在界面显示时,父节点和子节点之间共用的边不画,其他的边都画出来,就能画出一个迷宫。
之后就是想一下该怎么实现这样一棵树。
首要的两个问题:
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 13 /* 迷宫由一个一个格子组成,格子之间的边为迷宫的墙。 14 * 将迷宫视为在这些格子上构造的树,每个格子都是树上的一个节点。 15 * 则任意两个格子间有且只有一条无环的路径。 16 * 迷宫的构建过程即是在这些格子上随机构造一棵树的过程。 17 * */ 18 19 // 格子 20 class Lattice { 21 static final int INTREE = 1; 22 static final int NOTINTREE = 0; 23 private int x = -1; // 格子的位置,在第几行 24 private int y = -1; // 第几列 25 private int flag = NOTINTREE; // flag,标识格子是否已加入树中 26 private Lattice father = null; // 格子的父亲节点 27 public Lattice(int xx, int yy) { 28 x = xx; 29 y = yy; 30 } 31 public int getX() { 32 return x; 33 } 34 public int getY() { 35 return y; 36 } 37 public int getFlag() { 38 return flag; 39 } 40 public Lattice getFather() { 41 return father; 42 } 43 public void setFather(Lattice f) { 44 father = f; 45 } 46 public void setFlag(int f) { 47 flag = f; 48 } 49 public String toString() { 50 return new String("(" + x + "," + y + ")\n"); 51 } 52 } 53 public class Maze extends JPanel { 54 private static final long serialVersionUID = -8300339045454852626L; 55 private int NUM, width, padding; // NUM:迷宫大小;width:每个格子的宽度和高度 56 private Lattice[][] maze; 57 private int ballX, ballY; // 球的位置,在第几行第几列格子上 58 private boolean drawPath = false; // flag,标识是否画出路径 59 Maze(int m, int wi, int p) { 60 NUM = m; 61 width = wi; 62 padding = p; 63 maze = new Lattice[NUM][NUM]; 64 for (int i = 0; i <= NUM - 1; i++) 65 for (int j = 0; j <= NUM - 1; j++) 66 maze[i][j] = new Lattice(i, j); 67 createMaze(); 68 setKeyListener(); 69 this.setFocusable(true); 70 } 71 // 初始化游戏,重开一局时使用 72 private void init() { 73 for (int i = 0; i <= NUM - 1; i++) 74 for (int j = 0; j <= NUM - 1; j++) { 75 maze[i][j].setFather(null); 76 maze[i][j].setFlag(Lattice.NOTINTREE); 77 } 78 ballX = 0; 79 ballY = 0; 80 drawPath = false; 81 createMaze(); 82 // setKeyListener(); 83 this.setFocusable(true); 84 repaint(); 85 } 86 // 由格子的行数,得到格子中心点的像素X座标 87 public int getCenterX(int x) { 88 return padding + x * width + width / 2; 89 } 90 // 由格子的列数,得到格子中心点的像素Y座标 91 public int getCenterY(int y) { 92 return padding + y * width + width / 2; 93 } 94 95 public int getCenterX(Lattice p) { 96 return padding + p.getY() * width + width / 2; 97 } 98 public int getCenterY(Lattice p) { 99 return padding + p.getX() * width + width / 2; 100 } 101 // 检查是否到达最后一个格子,若是则走出了迷宫,重开一局游戏 102 private void checkIsWin() { 103 if (ballX == NUM - 1 && ballY == NUM - 1) { 104 JOptionPane.showMessageDialog(null, "YOU WIN !", "你走出了迷宫。", 105 JOptionPane.PLAIN_MESSAGE); 106 init(); 107 } 108 } 109 // 移动小球,c为按键码 110 synchronized private void move(int c) { 111 int tx = ballX, ty = ballY; 112 // System.out.println(c); 113 switch (c) { 114 case KeyEvent.VK_LEFT : 115 ty--; 116 break; 117 case KeyEvent.VK_RIGHT : 118 ty++; 119 break; 120 case KeyEvent.VK_UP : 121 tx--; 122 break; 123 case KeyEvent.VK_DOWN : 124 tx++; 125 break; 126 case KeyEvent.VK_SPACE : 127 if (drawPath == true) { 128 drawPath = false; 129 } else { 130 drawPath = true; 131 } 132 break; 133 default : 134 } 135 // 若移动后未出界且格子之间有路径,则进行移动,更新小球位置,否则移动非法 136 if (!isOutOfBorder(tx, ty) 137 && (maze[tx][ty].getFather() == maze[ballX][ballY] 138 || maze[ballX][ballY].getFather() == maze[tx][ty])) { 139 ballX = tx; 140 ballY = ty; 141 } 142 } 143 private void setKeyListener() { 144 this.addKeyListener(new KeyAdapter() { 145 public void keyPressed(KeyEvent e) { 146 int c = e.getKeyCode(); 147 move(c); 148 repaint(); 149 checkIsWin(); 150 } 151 }); 152 } 153 // 是否出界 154 private boolean isOutOfBorder(Lattice p) { 155 return isOutOfBorder(p.getX(), p.getY()); 156 } 157 private boolean isOutOfBorder(int x, int y) { 158 return (x > NUM - 1 || y > NUM - 1 || x < 0 || y < 0) ? true : false; 159 } 160 // 获取格子的邻居格子 161 private Lattice[] getNeis(Lattice p) { 162 final int[] adds = {-1, 0, 1, 0, -1}; 163 if (isOutOfBorder(p)) { 164 return null; 165 } 166 Lattice[] ps = new Lattice[4]; // 四个邻居格子,顺序为上右下左,出界的邻居为null 167 int xt; 168 int yt; 169 for (int i = 0; i <= 3; i++) { 170 xt = p.getX() + adds[i]; 171 yt = p.getY() + adds[i + 1]; 172 if (isOutOfBorder(xt, yt)) 173 continue; 174 ps[i] = maze[xt][yt]; 175 } 176 return ps; 177 } 178 // 构建随机树,创建迷宫 179 private void createMaze() { 180 // 随机选一个格子作为树的根 181 Random random = new Random(); 182 int rx = Math.abs(random.nextInt()) % NUM; 183 int ry = Math.abs(random.nextInt()) % NUM; 184 // 深度优先遍历 185 Stack<Lattice> s = new Stack<Lattice>(); 186 Lattice p = maze[rx][ry]; 187 Lattice neis[] = null; 188 s.push(p); 189 while (!s.isEmpty()) { 190 p = s.pop(); 191 p.setFlag(Lattice.INTREE); 192 neis = getNeis(p); 193 int ran = Math.abs(random.nextInt()) % 4; 194 for (int a = 0; a <= 3; a++) { 195 ran++; 196 ran %= 4; 197 if (neis[ran] == null || neis[ran].getFlag() == Lattice.INTREE) 198 continue; 199 s.push(neis[ran]); 200 neis[ran].setFather(p); 201 } 202 } 203 } 204 // 抹掉两个格子之间的边 205 private void clearFence(int i, int j, int fx, int fy, Graphics g) { 206 int sx = padding + ((j > fy ? j : fy) * width), 207 sy = padding + ((i > fx ? i : fx) * width), 208 dx = (i == fx ? sx : sx + width), 209 dy = (i == fx ? sy + width : sy); 210 if (sx != dx) { 211 sx++; 212 dx--; 213 } else { 214 sy++; 215 dy--; 216 } 217 g.drawLine(sx, sy, dx, dy); 218 } 219 // 画迷宫 220 protected void paintComponent(Graphics g) { 221 super.paintComponent(g); 222 // 画NUM*NUM条黑线 223 for (int i = 0; i <= NUM; i++) { 224 g.drawLine(padding + i * width, padding, padding + i * width, 225 padding + NUM * width); 226 } 227 for (int j = 0; j <= NUM; j++) { 228 g.drawLine(padding, padding + j * width, padding + NUM * width, 229 padding + j * width); 230 } 231 // 使用背景色,在有路径的格子之间画边,把墙抹掉 232 g.setColor(this.getBackground()); 233 for (int i = NUM - 1; i >= 0; i--) { 234 for (int j = NUM - 1; j >= 0; j--) { 235 Lattice f = maze[i][j].getFather(); 236 if (f != null) { 237 int fx = f.getX(), fy = f.getY(); 238 clearFence(i, j, fx, fy, g); 239 } 240 } 241 } 242 // 画左上角的入口 243 g.drawLine(padding, padding + 1, padding, padding + width - 1); 244 int last = padding + NUM * width; 245 // 画右下角出口 246 g.drawLine(last, last - 1, last, last - width + 1); 247 // 画小球 248 g.setColor(Color.RED); 249 g.fillOval(getCenterX(ballY) - width / 3, getCenterY(ballX) - width / 3, 250 width / 2, width / 2); 251 if (drawPath == true) 252 drawPath(g); 253 } 254 255 private void drawPath(Graphics g) { 256 Color PATH_COLOR = Color.ORANGE, BOTH_PATH_COLOR = Color.PINK; 257 if (drawPath == true) 258 g.setColor(PATH_COLOR); 259 else 260 g.setColor(this.getBackground()); 261 Lattice p = maze[NUM - 1][NUM - 1]; 262 while (p.getFather() != null) { 263 p.setFlag(2); 264 p = p.getFather(); 265 } 266 g.fillOval(getCenterX(p) - width / 3, getCenterY(p) - width / 3, 267 width / 2, width / 2); 268 p = maze[0][0]; 269 while (p.getFather() != null) { 270 if (p.getFlag() == 2) { 271 p.setFlag(3); 272 g.setColor(BOTH_PATH_COLOR); 273 } 274 g.drawLine(getCenterX(p), getCenterY(p), getCenterX(p.getFather()), 275 getCenterY(p.getFather())); 276 p = p.getFather(); 277 } 278 g.setColor(PATH_COLOR); 279 p = maze[NUM - 1][NUM - 1]; 280 while (p.getFather() != null) { 281 if (p.getFlag() == 3) 282 break; 283 g.drawLine(getCenterX(p), getCenterY(p), getCenterX(p.getFather()), 284 getCenterY(p.getFather())); 285 p = p.getFather(); 286 } 287 } 288 public static void main(String[] args) { 289 final int n = 30, width = 600, padding = 20, LX = 200, LY = 100; 290 JPanel p = new Maze(n, (width - padding - padding) / n, padding); 291 JFrame frame = new JFrame("MAZE(按空格键显示或隐藏路径)"); 292 frame.getContentPane().add(p); 293 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 294 frame.setSize(width + padding, width + padding + padding); 295 frame.setLocation(LX, LY); 296 frame.setVisible(true); 297 } 298 }
程序完成于大三上学期。
随笔写于2016.5.8