For this week’s assignment, I chose to make a random self-avoiding walker. First, I started by looking at the P5JS example of it and took inspiration from it.
But it wasn’t enough. So, I have started looking for ways to make the walk not get stuck. For that, I have modified the approach to continuously attempt to find a path by using a backtracking method. It took me a few tries, but I have eventually got there.
After everything, I have added the function to change colors everytime it changes directions. This was not as hard because we have tried it in class.
let spacing = 20; let cols, rows; let x, y; let grid; let allOptions = [ { dx: 0, dy: 1 }, { dx: 1, dy: 0 }, { dx: 0, dy: -1 }, { dx: -1, dy: 0 }, ]; let stack = []; let currentColor; function setup() { createCanvas(400, 400); cols = width / spacing; rows = height / spacing; x = floor(cols / 2); y = floor(rows / 2); background(51); grid = Array.from({ length: cols }, () => Array(rows).fill(false)); grid[x][y] = true; stack.push([x, y]); currentColor = pastelColor(); } function draw() { stroke(currentColor); strokeWeight(spacing * 0.5); point(x * spacing, y * spacing); let options = allOptions.filter((option) => isValid(x + option.dx, y + option.dy) ); if (options.length > 0) { let step = random(options); strokeWeight(1); stroke(currentColor); line( x * spacing, y * spacing, (x + step.dx) * spacing, (y + step.dy) * spacing ); x += step.dx; y += step.dy; grid[x][y] = true; stack.push([x, y]); currentColor = pastelColor(); } else { if (stack.length > 1) { stack.pop(); [x, y] = stack[stack.length - 1]; } else { noLoop(); } } } function isValid(i, j) { return grid[i]?.[j] === false && i >= 0 && i < cols && j >= 0 && j < rows; } function pastelColor() { return color(random(200, 255), random(200, 255), random(200, 255)); }
For the future, I think that I would like to make it more complex. Maybe I can make two of them and make it collide and when they do something happens. Until then, I am pretty pleased with the outcome