xxxxxxxxxx
94
class Rule {
constructor(value) {
this.value = value;
this.ruleSet = this._decimalToBinaryArray(value);
}
_decimalToBinaryArray(value) {
return value.toString(2).padStart(8, "0").split("").reverse().map(Number);
}
compute(left, center, right) {
const value = left * 4 + center * 2 + right;
return this.ruleSet[value];
}
}
class Row {
constructor(size) {
this.size = size;
this.cells = this._createRandomCells(size);
}
_createRandomCells(size) {
return Array.from({ length: size }, () => Math.floor(Math.random() * 2));
}
applyRule(rule) {
const newCells = [];
for (var i = 0; i < this.size; i++) {
const left = this.cells[(i - 1 + this.size) % this.size];
const center = this.cells[i];
const right = this.cells[(i + 1) % this.size];
newCells.push(rule.compute(left, center, right));
}
this.cells = newCells;
}
}
class ColorRow {
constructor(sizeOrRows) {
const size = sizeOrRows;
this.size = size;
this.rows = [new Row(size), new Row(size), new Row(size)];
}
applyRule(rule) {
this.rows.map((i) => i.applyRule(rule));
}
*getCellColors() {
for (let i = 0; i < this.size; i++) {
yield this._getCellColorAt(i);
}
}
_getCellColorAt(index) {
return color(
this.rows[0].cells[index] * 255,
this.rows[1].cells[index] * 255,
this.rows[2].cells[index] * 255
);
}
}
const cellCount = 200;
const cellSize = 4;
const width = cellSize * cellCount;
const height = 450;
const rule = new Rule(30);
const row = new ColorRow(cellCount);
let y = 0;
function setup() {
createCanvas(width, height);
noStroke();
}
function draw() {
row.applyRule(rule);
let x = 0;
for (const cellColor of row.getCellColors()) {
fill(cellColor);
square(x, y, cellSize);
x += cellSize;
}
y += cellSize;
if (y >= height) noLoop();
}