建造迷宫

Jür*_*aul 1 java events awt paint frame

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

在此输入图像描述

我刚刚开始Frame尝试抓住这样做的想法.

dav*_*veb 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我会用块(正方形)绘制这个迷宫,而不是线条.阻挡瓷砖的暗块,空瓷砖的透明块.

要画画,做这样的事情.

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);
            }
        }
    )

}
Run Code Online (Sandbox Code Playgroud)