Cell.java
Below is the syntax highlighted version of Cell.java
from §4.3 Linked Structures.
/*************************************************************************
*
* A cell in a 2d grid. A helper class for Maze.java.
*
*************************************************************************/
public class Cell {
private Cell north, east, south, west; // neighboring cells
private boolean northWall, eastWall; // does the wall to the north exist
private boolean southWall, westWall;
private boolean visited;
private double x, y; // Euclidean coordinates of cell center
public Cell(double x, double y) {
this.x = x;
this.y = y;
northWall = eastWall = southWall = westWall = true;
}
void setVisited(boolean b) { visited = b; }
boolean isVisited() { return visited; }
void setNeighbors(Cell north, Cell east, Cell south, Cell west) {
this.north = north;
this.east = east;
this.south = south;
this.west = west;
}
Cell getNorth() { if (!northWall) return north; else return null; }
Cell getEast() { if (!eastWall) return east; else return null; }
Cell getSouth() { if (!southWall) return south; else return null; }
Cell getWest() { if (!westWall) return west; else return null; }
/********************************************************************
* Find a random neighbor that leads to a previously unvisited
* neighbor. If you find one, delete the wall and return the
* neighbor; otherwise return null.
********************************************************************/
Cell deleteRandomWall() {
if (north.visited && east.visited && south.visited && west.visited)
return null;
// pick random neighbor (could use Knuth's trick instead)
while (true) {
double r = Math.random();
if (r < 0.25 && !north.visited) {
northWall = north.southWall = false;
return north;
}
else if (r >= 0.25 && r < 0.50 && !east.visited) {
eastWall = east.westWall = false;
return east;
}
else if (r >= 0.5 && r < 0.75 && !south.visited) {
southWall = south.northWall = false;
return south;
}
else if (r >= 0.75 && r < 1.00 && !west.visited) {
westWall = west.eastWall = false;
return west;
}
}
}
/********************************************************************
* Draw cell cornered at (x, y) of given size.
********************************************************************/
public void spot(Draw d, double size) {
d.moveTo(x + size / 2, y + size / 2);
d.spot(size / 2);
}
/********************************************************************
* Draw cell cornered at (x, y) of given size.
********************************************************************/
public void draw(Draw d, double size) {
d.moveTo(x, y);
// south wall
if (southWall) d.moveTo(x + size, y);
else d.lineTo(x + size, y);
// east wall
if (eastWall) d.moveTo(x + size, y + size);
else d.lineTo(x + size, y + size);
// north wall
if (northWall) d.moveTo(x, y + size);
else d.lineTo(x, y + size);
// west wall
if (westWall) d.moveTo(x, y);
else d.lineTo(x, y);
}
}