建造迷宫

时间:2012-04-13 06:50:04

标签: java events awt frame paint

起初我觉得很容易,但是当我开始这样做时,我不知道如何继续。我的想法是使用面板,然后绘制粗线,但那么绘制墙壁的正确方法是什么,让我的角色不会移动到那些墙壁之外?我无法想象我怎么可能这样做。这是一个迷宫的草图,以说明我将如何做到这一点:

enter image description here

我刚刚开始使用Frame并且仍然试图抓住这样做的想法。

1 个答案:

答案 0 :(得分: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);
            }
        }
    )

}
相关问题