我正在尝试创建一个 DFS 生成的迷宫。我首先制作一个具有 4 条线(顶部、右侧、底部和左侧)的 Cell
对象。然后我将这些线绘制到迷宫 JPanel
上。我的问题是,大多数单元格看起来都很好,但 JPanel 的左侧和顶部有粗线,我不知道如何使其成为常规网格。
这是我在其中创建行的单元格
:
boolean[] walls = {true, true, true, true};
// Draw the lines of one cell with w width and h height
void drawCell(Graphics g, int w, int h){
// Set the color of the lines to white
g.setColor(Color.WHITE);
// If the top wall exists draw a top line
if (walls[0]) {
g.drawLine(TopLeftX(), TopLeftY(), TopRightX(w), TopRightY());
}
// If a right wall exists draw a right line
if (walls[1]) {
g.drawLine(TopRightX(w), TopRightY(), BotRightX(w), BotRightY(h));
}
// If a bottom wall exists draw a bottom line
if (walls[2]) {
g.drawLine(BotRightX(w), BotRightY(h), BotLeftX(), BotLeftY(h));
}
// If a left wall exists draw a left line
if (walls[3]) {
g.drawLine(BotLeftX(), BotLeftY(h), TopLeftX(), TopLeftY());
}
}
// Set each coordinate for the lines, these will make a square that
// is w wide and h high
private int TopLeftX() { return i; }
private int TopLeftY() { return j; }
private int TopRightX(int w){ return i * w; }
private int TopRightY() { return j; }
private int BotRightX(int w){ return i * w; }
private int BotRightY(int h){ return j * h; }
private int BotLeftX() { return i; }
private int BotLeftY(int h) { return j * h; }
w
是单元格的宽度,h
是单元格的高度。
这是我画线的 MazeView
JPanel
:
class MazeView extends JPanel{
private Cell grid[][];
private Cell cell;
private int row;
private int col;
private int width = 600;
private int height = 580;
// Create a maze view JPanel that is rows tall and cols wide
MazeView(int rows, int cols){
super.setBackground(Color.BLACK);
super.setLayout(new GridLayout(rows, cols));
newGrid(rows, cols);
}
// Paint all the cells
public void paintComponent(Graphics g){
super.paintComponent(g);
// Get the height and width of each cell
int h = height / getRows();
int w = width / getCols();
// Loop to draw each cell
for (int i = 0; i <= getRows(); i++){
for (int j = 0; j <= getCols(); j++){
grid[i][j].drawCell(g, w, h);
}
}
}
}
我很感激我能得到的任何帮助。
运行时我的网格如下所示:
最佳答案
看看g.drawLine(TopLeftX(), TopLeftY(), TopRightX(w), TopRightY());
- 解析您获得坐标的这些方法的值i ,j,i*w,j
。假设 i
和 j
是您要绘制一条线的单元格位置
- 对于单元格 0/0,从 0/0 到 0/0
- 对于单元格 1/0,从 1/0 到 w/0
- 对于单元格 0/1,从 0/1 到 0/1
- 对于单元 2/2,从 2/2 到 2*w/2
等等
因此,您需要更正所有 4 个绘图命令的坐标计算。
假设i
和j
是单元格的网格坐标,w
和h
是单元格坐标的尺寸左上角将是 i * w
和 j * h
,右下角将是 (i + 1) * w
和 (j + 1) * h
。
示例:
0 3 6 9
--------------> x
0 | +---+---+---+
| |0/0|1/0|2/0|
3 | +---+---+---+
| |0/1|1/1|2/1|
6 | +---o---+---+
| |0/2|1/2|2/2|
9 | +---+---O---+
V
y
假设每个单元格的宽度和高度均为 3 像素。因此底部中心单元的坐标是:
- 左上角 (
o
):x = i * w = 1 * 3 = 3
和y = j * h = 2 * 3 = 6
- 右下角 (
O
):x = (i + 1) * w = (1 + 1) * 3 = 6
和y = (j + 1) * h = (2 + 1) * 3 = 9
。
关于java - 在 Java 中绘制线条以创建单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46977613/