gpt4 book ai didi

java - 在JPanel中画一个迷宫

转载 作者:行者123 更新时间:2023-11-30 03:12:36 25 4
gpt4 key购买 nike

我正在用 Java 制作一个随机迷宫生成器。用户可以选择算法,然后按“生成”按钮以在 JFrame 中心查看生成的迷宫。迷宫生成后,我必须将其绘制在 JPanel 内。如果我们考虑使用回溯算法的 dfs,对于每个单元格,我有 4 个 boolean 变量,指示该单元格是否有向上、向下、向左、向右的墙。该算法运行并相应地移除这些墙(梦剧场\m/)。现在每个单元格都应该具有绘制迷宫所需的信息,但我不知道该怎么做。我无法使用索引来绘制线条。

这是代码草案:

BufferedImage image = new BufferedImage(MAZE_PANEL_DIM, MAZE_PANEL_DIM,BufferedImage.TYPE_INT_RGB);
Graphics g2 = image.getGraphics();
g2.setColor(Color.WHITE);
g2.fillRect(0, 0, MAZE_PANEL_DIM, MAZE_PANEL_DIM);
g2.setColor(Color.BLACK);
for(int i = 0; i < Maze.DIM; i++) {
for(int j = 0; j < Maze.DIM; j++) { // Note: the size of the cell is CELL_DIM = 600 / Maze.DIM
Cell cell = cells[i][j];
if(cell.hasRightWall()) {
// draw vertical line on the right border of the cell
}
if(cell.hasDownWall()) {
// draw horizontal line on the bottom border of the cell
}
if(cell.hasLeftWall()) {
// draw vertical line on the left border of the cell
}
if(cell.hasUpWall()) {
// draw horizontal line on the top border of the cell
}
}
}

更新

好吧,解决方案应该是这样的......

for(int i = 0; i < Maze.DIM; i++) {          
for(int j = 0; j < Maze.DIM; j++) { // Note: the size of the cell is CELL_DIM = 600 / Maze.DIM
Cell cell = cells[i][j];
if(cell.hasRightWall()) {
// draw vertical line on the right border of the cell
g2.drawLine(j * CELL_DIM + CELL_DIM, i * CELL_DIM, CELL_DIM + j * CELL_DIM, CELL_DIM + i * CELL_DIM);
}
if(cell.hasDownWall()) {
// draw horizontal line on the bottom border of the cell
g2.drawLine(j * CELL_DIM, i * CELL_DIM + CELL_DIM, j * CELL_DIM + CELL_DIM, i * CELL_DIM + CELL_DIM);
}
if(cell.hasLeftWall()) {
// draw vertical line on the left border of the cell
g2.drawLine(j * CELL_DIM, i * CELL_DIM, j * CELL_DIM, CELL_DIM + i * CELL_DIM);
}
if(cell.hasUpWall()) {
// draw horizontal line on the top border of the cell
g2.drawLine(j * CELL_DIM, i * CELL_DIM , CELL_DIM + j * CELL_DIM, i * CELL_DIM);
}
}
}

问题是右边框和下边框没有被绘制。

最佳答案

docs对于 Graphics 类来说:

The graphics pen hangs down and to the right from the path it traverses.

因此,如果您尝试在迷宫的右侧边缘绘制单元格的右侧边框,Graphics 笔将位于您的 BufferedImage 之外>。解决方案是对线段的坐标进行边界检查,并确保所有线条都绘制在图像内。

if (cell.hasRightWall()) {
int fromX = j * CELL_DIM + CELL_DIM;
int fromY = i * CELL_DIM;

if (fromX >= image.getWidth()) {
fromX = image.getWidth() - 1;
}

g2.drawLine(fromX, fromY, fromX, fromY + CELL_DIM);
}

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com