xxxxxxxxxx
105
// Rule 30
//
// Jared Donovan 2022
//
// Implementation of the 'rule 30' cellular automata
//
let siz = 10;
let cells = [];
let rows, cols;
let idx = 0;
let rule = [
[false, true, true, true],
[true, false, false, false]
];
function setup() {
createCanvas(400, 400);
//stroke(50);
noStroke();
rows = height / siz;
cols = width / siz;
for (let row = 0; row < rows; row++){
cells.push([])
for (let col = 0; col < cols; col++){
cells[row][col] = false;
}
}
// Set the middle one true to begin with
cells[0][floor(cols / 2)] = true;
}
function draw() {
background(220);
if (idx < rows - 1){
idx += 1;
} else {
// Copy each row down one
cells.shift();
cells.push(new Array(cols).fill(false));
}
drawCells();
//stroke(255, 0, 0);
//line(0, idx * siz, width, idx * siz);
// Calculate next row (shown on next draw loop)
for (let col = 0; col < cols; col++){
let row = idx;
let prevRow = idx - 1;
// Wrapping
// let a = cells[prevRow][((col - 1) + cols) % cols] ? 1:0;
// let b = cells[prevRow][col ] ? 2 : 0;
// let c = cells[prevRow][(col + 1) % cols] ? 1 : 0;
let a = cells[prevRow][col - 1] ? 1:0;
let b = cells[prevRow][col ] ? 2 : 0;
let c = cells[prevRow][(col + 1)] ? 1 : 0;
if (col == 0){
a = 0;
if (b){
a = random(100) > 20 ? 1 : 0;
}
}
if (col == cols - 1){
c = 0;
if (b){
c = random(100) > 20 ? 1 : 0;
}
}
cells[row][col] = rule[c][a + b];
}
//
//noLoop();
}
function drawCells(){
for (let row = 0; row < rows; row++){
for (let col = 0; col < cols; col++){
if (cells[row][col]){
fill(0);
} else {
fill(255);
}
//stroke(50);
square(col * siz, row * siz, siz);
}
}
}
function keyPressed(){
if (key == ' ' ){
loop();
}
}