xxxxxxxxxx
91
const GRID_SIZE = 8;
var grids = [
null,
null,
];
var grid = null;
var grid_w = null;
var grid_h = null;
var b = 1;
var size = 3;
function setup() {
createCanvas(400, 400);
grid_w = Math.floor(width / GRID_SIZE);
grid_h = Math.floor(height / GRID_SIZE);
grids[0] = (new Array(grid_w * grid_h)).fill(0);
grids[1] = (new Array(grid_w * grid_h)).fill(0);
grids[0][(2 * grid_w) + 2] = 1;
grid = grids[0];
frameRate(60);
noStroke();
colorMode(HSB);
}
function draw() {
background(32);
drawGrid();
updateGrid();
grid = grids[grid == grids[0] ? 1 : 0];
}
function mouseDragged() {
const my = Math.floor(mouseY / GRID_SIZE);
const mx = Math.floor(mouseX / GRID_SIZE);
for (let y = my - size; y < my + size; y++) {
for (let x = mx - size; x < mx + size; x++) {
grid[(y * grid_w) + x] = b;
}
}
b += 1;
if (b > 360) {
b = 1;
}
}
function updateGrid() {
const newIdx = grid == grids[0] ? 1 : 0;
for (i = 0; i < grid.length; i++) {
const y = Math.floor(i / grid_w);
if (grids[newIdx][i] === 0) {
if (
grid[i] !== 0
&& y !== grid_h - 1
&& (
grid[i + grid_w] === 0
|| grid[i + grid_w - 1] === 0
|| grid[i + grid_w + 1] === 0
)
) {
if (grid[i + grid_w] === 0) {
grids[newIdx][i] = 0;
grids[newIdx][i + grid_w] = grid[i];
} else if (grid[i + grid_w - 1] === 0 && grid[i + grid_w + 1] === 0) {
grids[newIdx][i] = 0;
grids[newIdx][i + grid_w + random([-1, 1])] = grid[i];
} else if (grid[i + grid_w - 1] === 0) {
grids[newIdx][i] = 0;
grids[newIdx][i + grid_w - 1] = grid[i];
} else if (grid[i + grid_w + 1] === 0) {
grids[newIdx][i] = 0;
grids[newIdx][i + grid_w + 1] = grid[i];
}
} else {
grids[newIdx][i] = grid[i];
}
}
grid[i] = 0;
}
}
function drawGrid() {
for (i = 0; i < grid_w * grid_h; i++) {
if (grid[i] !== 0) {
const x = i % grid_w;
const y = Math.floor(i / grid_w);
fill(grid[i], 100, 100);
rect(x * GRID_SIZE, y * GRID_SIZE, GRID_SIZE, GRID_SIZE);
}
}
}