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 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

 

END


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM