int cols, rows; int w = 20; ArrayList<Cell> grid = new ArrayList<Cell>(); ArrayList<Cell> stack = new ArrayList<Cell>(); Cell current; void setup() { size(820, 820); cols = floor(width/w); rows = floor(height/w); for (int j = 0; j < rows; j++) { for (int i = 0; i < cols; i++) { Cell cell = new Cell(i, j); grid.add(cell); } } //initialized the wall for (int j = 0; j < rows/2+1; j++) { for (int i = 0; i < cols; i++) { grid.get(index(i, j*2 )).wall = true; } } for (int j = 0; j < rows; j++) { for (int i = 0; i < cols/2+1; i++) { grid.get(index(i*2, j )).wall = true; } } //frameRate(5); current = grid.get(index(1, 1)); } void draw() { background(51); for (int j = 0; j < rows; j++) { for (int i = 0; i < cols; i++) { grid.get(index(i, j)).show(); } } current.visited = true; current.highlight(); // STEP 1 Cell next = current.checkNeighbors(); if (next != null) { next.visited = true; // STEP 2 stack.add(current); // STEP 3 removeWalls(current, next); // STEP 4 current = next; } else if (stack.size() > 0) { current = stack.remove(stack.size()-1); } } int index(int i, int j) { if (i < 0 || j < 0 || i > cols-1 || j > rows-1) { return 0; } return i + j * cols; } void removeWalls(Cell a, Cell b) { int x = a.i - b.i; if (x == 2) { grid.get(index((a.i+b.i)/2, a.j)).wall = false; } else if (x == -2) { grid.get(index((a.i+b.i)/2, a.j)).wall = false; } int y = a.j - b.j; if (y == 2) { grid.get(index(a.i, (a.j+b.j)/2)).wall = false; } else if (y == -2) { grid.get(index(a.i, (a.j+b.j)/2)).wall = false; } }
class Cell {
int i, j;
boolean wall = false;
boolean visited = false;
ArrayList<Cell> neighborAstars = new ArrayList<Cell>();
Cell(int i_, int j_) {
i = i_;
j = j_;
}
Cell checkNeighbors() {
ArrayList<Cell> neighbors = new ArrayList<Cell>();
Cell top = grid.get(index(i, j-2));
Cell right = grid.get(index(i+2, j));
Cell bottom = grid.get(index(i, j+2));
Cell left = grid.get(index(i-2, j));
if (top != null && !top.visited && !wall) {
neighbors.add(top);
}
if (right != null && !right.visited && !wall) {
neighbors.add(right);
}
if (bottom != null && !bottom.visited && !wall) {
neighbors.add(bottom);
}
if (left != null && !left.visited && !wall) {
neighbors.add(left);
}
if (neighbors.size() > 0) {
int r = floor(random(0, neighbors.size()));
return neighbors.get(r);
} else {
return null;
}
}
void show() {
int x = i*w;
int y = j*w;
stroke(255);
if(wall){
noStroke();
fill(0, 0, 255, 100);
rect(x, y, w, w);
}
if(!wall){
noStroke();
fill(255);
rect(x, y, w, w);
}
if (visited) {
noStroke();
fill(255);
rect(x, y, w, w);
}
}
void highlight() {
int x = i*w;
int y = j*w;
noStroke();
fill(0, 0, 255, 100);
rect(x, y, w, w);
}
}
why the grid(0,0) always turn wall to !wall.