xxxxxxxxxx
171
const W = 10;
const H = 7;
const NUM_PATHS = 5;
let grid = [];
let belt = [];
function setup() {
createCanvas(600, 600);
generateBelt();
}
function draw() {
background(220);
drawBelt();
}
function mouseReleased() {
generateBelt();
}
function generateBelt() {
initGrid();
initBelt();
let numCompletePaths = 0;
while(numCompletePaths < NUM_PATHS) {
const path = [];
let prev = constrainH(int(random(H)));
let valid = true;
for(let i = 0; i < W; i ++) {
const curr = constrainH(prev + random([-1, 0, 1]));
const crosses = i > 0 && curr !== prev && grid[i-1][curr].isConnected(grid[i][prev]);
if(crosses) {
valid = false;
break;
}
path.push(curr);
prev = curr;
}
if(!valid) {
continue;
}
for(let i = 1; i < path.length; i ++) {
const p = path[i - 1];
const c = path[i];
grid[i-1][p].addConnection(grid[i][c]);
addToBeltLayer(belt[i-1], grid[i-1][p]);
addToBeltLayer(belt[i], grid[i][c]);
}
numCompletePaths ++;
}
// // strip out buggered ones
// for(let i = 0; i < W; i ++) {
// const layer = [];
// for(let j = 0; j < H; j ++) {
// const node = grid[i][j];
// if(i == W - 1) {
// let valid = true;
// for(let a of belt[belt.length - 1]) {
// if(!a.isConnected(node)) {
// valid = false;
// break;
// }
// }
// if(!valid) {
// continue;
// }
// } else if(node.connections.length == 0) {
// continue;
// }
// layer.push(node);
// }
// belt.push(layer);
// }
}
function initGrid() {
grid = [];
for(let i = 0; i < W; i ++) {
const layer = [];
for(let j = 0; j < H; j ++) {
layer.push(new Asteroid(frac(i, W), frac(j, H)));
}
grid.push(layer);
}
}
function initBelt() {
belt = [];
for(let i = 0; i < W; i ++) {
belt.push([]);
}
}
function addToBeltLayer(layer, asteroid) {
if(layer.indexOf(asteroid) !== -1) {
return;
}
layer.push(asteroid);
}
function frac(idx, total) {
return (idx + 1)/(total + 1);
}
function constrainH(h) {
return constrain(h, 0, H-1);
}
function drawBelt() {
for(let i = 0; i < W; i ++) {
const layer = belt[i];
layer.forEach(asteroid => {
asteroid.draw();
});
}
}
class Asteroid {
constructor(x, y) {
this.x = x;
this.y = y;
this.xOff = random(-10, 10);
this.yOff = random(-10, 10);
this.connections = [];
}
addConnection(asteroid) {
this.connections.push(asteroid);
}
isConnected(asteroid) {
return this.connections.indexOf(asteroid) !== -1;
}
draw() {
const x = this.x * width + this.xOff;
const y = this.y * height + this.yOff;
this.connections.forEach(other => {
const ox = other.x * width + other.xOff;
const oy = other.y * height + other.yOff;
line(x, y, ox, oy);
});
circle(x, y, 20);
}
}