xxxxxxxxxx
100
let allOptions = [
{ dx: 1, dy: 0 },
{ dx: -1, dy: 0 },
{ dx: 0, dy: 1 },
{ dx: 0, dy: -1 },
];
let x;
let y;
let size = 16;
let grid;
let spacing;
let cols, rows;
let direction = 0;
let margin = 10;
function make2DArray(cols, rows) {
let arr = new Array(cols);
for (let i = 0; i < arr.length; i++) {
arr[i] = new Array(rows);
}
return arr;
}
function setup() {
createCanvas(600, 600);
cols = size;
rows = size;
spacing = (width - margin * 2) / (size - 1);
x = 0;
y = 0;
background(51);
grid = make2DArray(cols, rows);
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
grid[i][j] = false;
}
}
grid[x][y] = true;
}
function isValid(i, j) {
if (i < 0 || i >= cols || j < 0 || j >= rows) {
return false;
}
return !grid[i][j];
}
function draw() {
translate(margin, margin);
noStroke();
fill(0, 31, 255);
circle(0, 0, 5);
stroke(255);
strokeWeight(spacing * 0.5);
//point(x * spacing, y * spacing);
let options = [];
for (let option of allOptions) {
let newX = x + option.dx;
let newY = y + option.dy;
if (isValid(newX, newY)) {
options.push(option);
}
}
if (options.length > 0) {
let step = random(options);
strokeWeight(1);
stroke(255);
noFill();
beginShape();
vertex(x * spacing, y * spacing);
x += step.dx;
y += step.dy;
vertex(x * spacing, y * spacing);
endShape();
grid[x][y] = true;
fill(0, 31, 255);
noStroke();
circle(x * spacing, y * spacing, 10);
if (grid[cols - 1][rows - 1] == true) {
noLoop();
}
} else {
//console.log(`I'm stuck!`);
background(51);
options = [];
x = 0;
y = 0;
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
grid[i][j] = false;
}
}
grid[x][y] = true;
}
}