var cell_size = 5;
var SIZE = 300;
function setup() {
createCanvas(SIZE, SIZE);
stroke(0, 0, 0);
numX = width / cell_size;
numY = height / cell_size;
cells = [];
for (var i = 0; i < numX; i++) {
cells[i] = [];
for (var j = 0; j < numY; j++) {
cells[i][j] = floor(random() * 2);
}
}
initialize();
generation = 0;
drawCells();
}
function draw() {
rule();
generation++;
drawCells();
}
var cells;
var numX;
var numY;
var generation;
function initialize() {
for (var i = 0; i < numX; i++) {
for (var j = 0; j < numY; j++) {
cells[i][j] = floor(random() * 2);
}
}
}
function drawCells() {
for (var i = 0; i < numX; i++) {
for (var j = 0; j < numY; j++) {
if (cells[i][j] == 1) fill(255, 255, 255);
if (cells[i][j] == 0) fill(0, 0, 0);
rect(i * cell_size, j * cell_size, cell_size, cell_size);
}
}
}
function rule() {
var temp = [];
for (var i = 0; i < numX; i++) {
temp[i] = [];
for (var j = 0; j < numX; j++) {
temp[i][j] = 0;
}
}
for (var i = 1; i < numX - 1; i++) {
for (var j = 1; j < numY - 1; j++) {
var neighbors = 0;
if (cells[i - 1][j - 1] == 1) neighbors++;
if (cells[i ][j - 1] == 1) neighbors++;
if (cells[i + 1][j - 1] == 1) neighbors++;
if (cells[i - 1][j ] == 1) neighbors++;
if (cells[i + 1][j ] == 1) neighbors++;
if (cells[i - 1][j + 1] == 1) neighbors++;
if (cells[i ][j + 1] == 1) neighbors++;
if (cells[i + 1][j + 1] == 1) neighbors++;
if (cells[i][j] == 1) {
if (neighbors == 0 || neighbors == 1) temp[i][j] = 0;
if (neighbors == 2 || neighbors == 3) temp[i][j] = 1;
if (neighbors >= 4) temp[i][j] = 0;
}
if (cells[i][j] == 0) {
if (neighbors == 3) temp[i][j] = 1;
}
}
}
for (var i = 0; i < numX; i++) {
for (var j = 0; j < numY; j++) {
cells[i][j] = temp[i][j];
}
}
}