在JPanel中画一个迷宫

时间:2015-10-23 12:07:16

标签: java swing maze

我正在使用Java制作随机迷宫生成器。用户可以选择算法,然后按“生成”按钮在JFrame的中心查看生成的迷宫。一旦生成迷宫,我必须在JPanel中绘制它。如果我们考虑使用回溯算法的dfs,对于每个单元格,我有4个布尔变量,指示单元格是否具有向上,向下,向左,向右的墙。 该算法相应地运行并移除这些墙(Dream Theater \ 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);
        }
    }
}

问题是没有画出右边框和下边框。

1 个答案:

答案 0 :(得分:2)

Graphics班的docs说:

  

图形笔从其遍历的路径向下和向右垂直。

因此,如果您尝试在迷宫的右侧边缘绘制单元格的右侧边框,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);
}