xxxxxxxxxx
59
let cells = [];
let cellSize = 2;
// let ruleSet = [0, 0, 0, 1, 1, 1, 1, 0]
// let ruleSet = parseInt('000011010', 2);
let ruleSet = parseInt('000011110', 2);
let generation = 0;
function setup() {
createCanvas(600, 600);
cells = Array(floor(width / cellSize)).fill(0);
cells[floor(cells.length / 2)] = 1;
}
function draw() {
for (let i = 0; i < cells.length; i++) {
if (cells[i] == 1) {
fill(0);
} else {
fill(0, 0);
}
noStroke();
rect(i * cellSize, generation * cellSize, cellSize, cellSize);
}
if (generation < height / cellSize) {
let nextGen = Array(cells.length).fill(0);
for (let i = 1; i < cells.length - 1; i++) {
let left = cells[i - 1];
let middle = cells[i];
let right = cells[i + 1];
nextGen[i] = rules(left, middle, right);
}
cells = nextGen;
generation++;
}
}
function rules(a, b, c) {
let index = (a << 2) | (b << 1) | c;
return (ruleSet >> index) & 1;
}
// // More clear code
// function rules(a, b, c) {
// if (a == 1 && b == 1 && c == 1) return ruleSet[0];
// if (a == 1 && b == 1 && c == 0) return ruleSet[1];
// if (a == 1 && b == 0 && c == 1) return ruleSet[2];
// if (a == 1 && b == 0 && c == 0) return ruleSet[3];
// if (a == 0 && b == 1 && c == 1) return ruleSet[4];
// if (a == 0 && b == 1 && c == 0) return ruleSet[5];
// if (a == 0 && b == 0 && c == 1) return ruleSet[6];
// // if (a == 0 && b == 0 && c == 0) return ruleSet[7];
// return ruleSet[7]
// }