Hi my friends,
I am trying to learn coding challenge Self-avoiding walk backtracing from Denial’s video 26:40 ; And converting the P5.js code to processing(java) code. But my code seems it is struggling on getting the array right and null pointer. Can anyone help me to figure out the problem?
Step[] allOptions =
{
new Step(1, 0), new Step(-1, 0), new Step(0, 1), new Step(0, -1)
};
Spot spot;
ArrayList<Spot> path = new ArrayList<Spot>();
Spot[][] grid;
int spacing = 20;
int cols, rows;
boolean isValid(int i, int j)
{
if(i < 0 || i >= cols || j < 0 || j >= rows)
{
return false;
}
return !grid[i][j].visited;
}
void setup()
{
size(400, 400);
cols = floor(width / spacing)+1;
rows = floor(height / spacing)+1;
background(0);
grid = new Spot[cols][rows];
for(int i = 0; i < cols; i++)
{
for(int j = 0; j < rows; j++)
{
grid[i][j] = new Spot(i, j);
}
}
spot = grid[0][0];
path.add(spot);
spot.visited = true;
}
void draw()
{
spot = spot.nextSpot();
if(spot == null)
{
ArrayList<Spot> stuck = new ArrayList<Spot>();
for(int i = path.size()-1; i >= 0; i--)
{
path.remove(i);
}
for(Spot sp: path)
{
stuck.add(sp);
}
stuck.clear();
for(int i = path.size()-1; i >= 0; i--)
{
spot = path.get(i);
}
}
else
{
path.add(spot);
spot.visited = true;
}
if(path.size() == cols*rows)
{
println("Solved!");
noLoop();
}
stroke(250, 0, 160);
strokeWeight(spacing*0.25);
noFill();
beginShape();
for(int i = 0; i < path.size(); i++)
{
vertex(path.get(i).x, path.get(i).y);
}
endShape();
stroke(250, 160, 0);
strokeWeight(spacing * 0.5);
point(spot.x, spot.y);
}
class Spot
{
int x, y;
int i, j;
boolean visited;
Step[] options;
Spot(int _i, int _j)
{
i = _i;
j = _j;
x = i * spacing;
y = j * spacing;
options = new Step[allOptions.length];
for(int i = 0; i < options.length; i++)
{
options[i] = allOptions[i];
}
visited = false;
}
void Clear()
{
visited = false;
for(int i = 0; i < options.length; i++)
{
options[i] = allOptions[i];
}
}
Spot nextSpot()
{
ArrayList<Step> validOptions = new ArrayList<Step>();
for(Step option: options)
{
int newX = i + option.dx;
int newY = j + option.dy;
if(isValid(newX, newY) && !option.tried)
{
validOptions.add(option);
}
println("newX: "+newX, "newY: "+newY);
}
println("valid options.size: " + validOptions.size());
if(validOptions.size() > 0)
{
int index = int(random(validOptions.size()-1));
Step step = validOptions.get(index);
step.tried = true;
return grid[i+step.dx][j+step.dy];
}
return null;
}
}
class Step
{
int dx, dy;
boolean tried;
Step(int x, int y)
{
dx = x;
dy = y;
tried = false;
}
}