Left-click: pause; Right-click: change BG; Middle-click: reset
xxxxxxxxxx
/**
* Self Avoiding Walk [With Backtracking] [Java/Pjs]
* Coding Challenge #162
* by The Coding Train / Daniel Shiffman
*
* https://TheCodingTrain.com/CodingChallenges/162-self-avoiding-walk.html
*
* Java Mode conversion by GoToLoop (2022/Feb/09) (v1.0.5)
*
* https://Discourse.Processing.org/t/
* converting-coding-challenge-self-avoiding-walk-backtracing-
* from-p5-js-to-processing-java/35047/4
*
* OpenProcessing.org/sketch/1475556
*/
import java.util.List;
final List<Spot> path = new ArrayList<Spot>();
Spot[][] grid;
Spot spot;
int matrix;
color bg;
boolean paused, finished;
void setup() {
size(650, 500);
noFill();
createGrid();
bg = (color) random(#000000);
}
void draw() {
if (finished) return;
getNextSpot();
drawGridPath();
}
void mousePressed() {
if (mouseButton == RIGHT) bg = (color) random(#000000);
else if (mouseButton == CENTER) createGrid();
else if (paused ^= true) noLoop();
else loop();
}
void createGrid() {
final int
rows = height / Spot.SPACING | 0,
cols = width / Spot.SPACING | 0;
grid = new Spot[rows][cols];
matrix = rows * cols;
for (int r = 0; r < rows; ++r) for (int c = 0; c < cols; ++c)
grid[r][c] = new Spot(r, c);
path.clear();
path.add(spot = grid[rows >> 1][cols >> 1]);
spot.visited = true;
}
void getNextSpot() {
spot = spot.nextSpot(grid);
if (spot != null) {
path.add(spot);
spot.visited = true;
} else {
final int len = path.size();
path.remove(len - 1).clear();
spot = path.get(len - 2);
}
if (path.size() == matrix) {
println("Solved!");
finished = true;
}
}
void drawGridPath() {
background(bg);
translate(Spot.HALF_SPACE, Spot.HALF_SPACE);
strokeWeight(Spot.QUARTER_SPACE);
stroke(-1);
beginShape();
for (final Spot spot : path) vertex(spot.x, spot.y);
endShape();
strokeWeight(Spot.HALF_SPACE);
stroke(250, 160, 0);
point(spot.x, spot.y);
}