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