2012-04-13 123 views
1

起初我以为这很容易,但当我开始做时,我不知道如何继续。我的想法是使用面板,然后画粗线条,但是画出墙壁的正确方法是什么,并使我的角色不会超越墙壁?我无法想象我能做到这一点。这里是一个迷宫的草图来说明如何我会做它:构建迷宫

enter image description here

我刚开始用Frame,仍然努力要抓住这样做的想法。

+0

你想创建随机迷宫或一个固定的迷宫?你已经有一种形式的碰撞检测? – ggfela 2012-04-13 06:57:36

+0

只是一个固定的迷宫。 – Michelle 2012-04-13 06:58:12

回答

5

首先,您需要一个代表您的迷宫的数据结构。那么你可以担心绘制它。

我建议一类是这样的:

class Maze { 
    public enum Tile { Start, End, Empty, Blocked }; 
    private final Tile[] cells; 
    private final int width; 
    private final int height; 

    public Maze(int width, int height) { 
     this.width = width; 
     this.height = height; 
     this.cells = new Tile[width * height]; 
     Arrays.fill(this.cells, Tile.Empty); 
    } 

    public int height() { 
     return height; 
    } 

    public int width() { 
     return width; 
    } 

    public Tile get(int x, int y) { 
     return cells[index(x, y)]; 
    } 

    public void set(int x, int y, Tile tile) { 
     Cells[index(x, y)] = tile; 
    } 

    private int index(int x, int y) { 
     return y * width + x; 
    } 
} 

然后,我会画这个迷宫积木(正方形),而不是线。一块暗块用于封闭的瓷砖,另一块用于清空瓷砖。

要绘画,做这样的事情。

public void paintTheMaze(graphics g) { 
    final int tileWidth = 32; 
    final int tileHeight = 32; 
    g.setColor(Color.BLACK); 

    for (int x = 0; x < maze.width(); ++x) { 
     for (int y = 0; y < maze.height(); ++y) { 
      if (maze.get(x, y).equals(Tile.Blocked)) (
       g.fillRect(x*tileWidth, y*tileHeight, tileWidth, tileHeight); 
      } 
     } 
    ) 

} 
+0

但是那么'没有越过这面墙'就怎么样? – Michelle 2012-04-13 08:43:31

+0

你也问如何解决迷宫? – daveb 2012-04-13 09:18:32

+0

不,我会用'KeyListeners'控制我的角色 – Michelle 2012-04-13 13:20:24