java - build 迷宫

标签 java events awt frame paint

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

enter image description here

我刚开始使用 Frame 并且仍在尝试掌握实现它的想法。

最佳答案

首先,您需要一个代表迷宫的数据结构。然后你就可以担心画它了。

我会建议这样的类(class):

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

然后我会用 block (方 block )而不是线来画这个迷宫。黑色方 block 代表被阻挡的方 block ,透明方 block 代表空方 block 。

要绘画,请执行以下操作。

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

}

关于java - build 迷宫,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10136426/

相关文章:

java - OpenGL ES 3.0 通过引用调用对象添加重力和 OnCLick 事件

java - 标签 <c :forEach/> si not doing anything

我可以在 Linux 上监视文件重命名事件吗?

javascript - touchstart 事件在滚动后停止工作

java - 如何在 jpanel 之间切换?

java - 如何仅在窗口完成时将窗口聚合结果发送到输出主题?

java - 线程 "main"java.lang.NoClassDefFoundError :javax/persistence/Cacheable 中出现异常

android - 如何更新 SeekBar 不触发 OnSeekBarChangeListener?

java - java.awt.Menu 的 RadioButtonMenuItem

java - Swing 未写字段警告(Java)