I'm making a random maze generator in Java. The user can select the algorithm and then press the "Generate" button to see the resulting maze in the center of the JFrame. Once the maze is generated i have to draw it inside a JPanel. If we consider the dfs with backtracking algorithm, for each cell i have 4 boolean variables indicating if the cell has a wall up, down, left, right. The algorithm runs and removes these walls (Dream Theater \m/) accordingly. Now each cell should have the information needed to draw the maze but i don't know how to do. I can't play with the indexes to draw the lines.
This is a draft of the code:
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
}
}
}
Update
Ok, the solutions should be like this...
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);
}
}
}
The problem is that the right border and the bottom border don't get drawn.
The docs for the Graphics
class say:
The graphics pen hangs down and to the right from the path it traverses.
So if you are trying to draw the right-hand border of a cell on the right-hand edge of the maze, the Graphics
pen will be outside of your BufferedImage
. The solution is to bounds-check the coordinates of the line segments and make sure all lines are drawn inside your image.
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);
}