I am making a maze and I would like to use the recursive method as defined here. However, I need some help as to how to randomly open up the lines once I randomly draw them. Right now I’m creating the lines (walls of the maze) simply by drawing them with their beginning and end x- and y-coordinates. I just can’t seem to find a simple way to “erase” (or “open up”) parts of the lines.
EDIT: Okay I need to be slightly more specific. How could I randomly select places on each line to “open up?”
EDIT 2: Here is some code of what I’m trying to do:
public static void draw() {
// picks a random spot in the rectangle
Random r = new Random();
int x0 = r.nextInt(w)
int y0 = r.nextInt(h)
// draws the 4 lines that are perpendicular to each other and meet
// at the selected point
StdDraw.line(x0, 0, x0, y0);
StdDraw.line(0, y0, x0, y0);
StdDraw.line(x0, h, x0, y0);
StdDraw.line(w, y0, x0, y0);
}
public static void main(String[] args) {
// set up the walls of the maze
// given w = width and h = height
StdDraw.setXscale(0, w);
StdDraw.setYscale(0, h);
StdDraw.line(0, 0, 0, h);
StdDraw.line(0, h, w, h);
StdDraw.line(w, h, w, 0);
StdDraw.line(w, 0, 0, 0);
draw();
}
Now I just need to figure out how to randomly select 3 of these lines, and for each line randomly erase a portion.
Assuming you’re using
swingand thepaintComponentmethod, you would set theGraphic‘s color to the background color and draw over the line again. Here’s an example:EDIT
I suppose you’re not creating the Maze in the
paintComponentmethod (or you’d end up with a new maze every time you repainted). So, I’d recommend creating a sub-class similar to below and storing instances of it in anArrayListfield of your main class. Then you can iterate through yourArrayListwhen you’re doing your panting.