xxxxxxxxxx
115
let matrix = [];
let n = 28;
let w;
let start
let current
let previous
let velocity
let d = 3
let diverted = false
function getNeighbors(position) {
let neighbors = [];
neighbors.push(p5.Vector.sub(position, createVector(1, 1)))
neighbors.push(p5.Vector.sub(position, createVector(1, 0)))
neighbors.push(p5.Vector.sub(position, createVector(1, -1)))
neighbors.push(p5.Vector.sub(position, createVector(0, -1)))
neighbors.push(p5.Vector.sub(position, createVector(-1, -1)))
neighbors.push(p5.Vector.sub(position, createVector(-1, 0)))
neighbors.push(p5.Vector.sub(position, createVector(-1, 1)))
neighbors.push(p5.Vector.sub(position, createVector(0, 1)))
return neighbors;
}
function isNeighborOfVelocity(current, neighbor, velocity) {
print(velocity.x, velocity.y)
let next = current.copy().add(velocity);
let nextNeighbors = getNeighbors(next.copy());
for (let n of nextNeighbors) {
if (n.x === neighbor.x && n.y === neighbor.y && matrix[n.x][n.y] !== 1 && matrix[neighbor.x][neighbor.y] !== 1) {
return true;
}
}
return false;
}
function setup() {
createCanvas(500, 500);
w = width/n;
start = createVector(15, 10);
velocity = createVector(0, 0);
for (let i = 0; i < n; i++) {
matrix[i] = []
for (let j = 0; j < n; j++) {
matrix[i][j] = 0
}
}
}
function draw() {
background(255);
frameRate(10);
let next = current
if (!current) {
current = start
matrix[current.x][current.y] = 1
}
if (previous && !diverted) {
velocity = current.copy().sub(previous)
}
let choices = [];
let neighbors = getNeighbors(current)
for (let neighbor of neighbors) {
if (isNeighborOfVelocity(current, neighbor, velocity)) {
choices.push(neighbor);
}
}
print("Choices:", choices.length);
let temp = random(choices)
print(temp)
if (temp) {
if (temp.x == start.x && temp.y == start.y) {
noLoop();
}
if (temp.x < d || temp.x > n - d) {
velocity = createVector(velocity.x * -1, velocity.y)
diverted = true
} else if (temp.y < d || temp.y > n - d) {
velocity = createVector(velocity.x, velocity.y * -1)
diverted = true
} else {
next = temp;
diverted = false
}
previous = current.copy();
current = next
if (current) {
matrix[current.x][current.y] = 1
}
}
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
stroke(0)
strokeWeight(1)
if (matrix[i][j] == 0) fill(255)
else fill(0, 0, 255)
rect(i * w, j * w, w, w)
}
}
}