xxxxxxxxxx
// make accessible to DPD 2025: Complexity I
// schien@mail.ncku.edu.tw
// adding comments to line 45, 48
// Cellular Automata (CA) in P5js
// demo for autonomy in Pearson (2011)
// schien@mail.ncku.edu.tw, Fall 2018
// updated revision
// schien@mail.ncku.edu.tw, Spring 2023
let _cellArray = []; // this will be a 2D array
let _numX, _numY;
let _cellSize = 10;
function setup() {
createCanvas(windowWidth, windowHeight);
//frameRate(4);
_numX = floor(width / _cellSize);
_numY = floor(height / _cellSize);
restart();
}
function draw() {
background(255);
for (let x = 0; x < _numX; x++) {
for (let y = 0; y < _numY; y++) {
_cellArray[x][y].calcNextState();
}
}
for (let x = 0; x < _numX; x++) {
for (let y = 0; y < _numY; y++) {
_cellArray[x][y].drawMe();
}
}
}
function mousePressed() {
restart();
}
function restart() {
// first, create a grid of cells
for (let x = 0; x < _numX; x++) {
_cellArray[x] = []; // initialize the _cellArray[0], _cellArray[1], ..., _cellArray[_numX-1]
for (let y = 0; y < _numY; y++) {
let newCell = new Cell(x, y);
_cellArray[x].push(newCell); // adding cells into _cellArray[x] to form _cellArray[x][0], _cellArray[x][1], ..., _cellArray[x][_numY-1]
}
}
// setup the neighbors of each cell
for (let x = 0; x < _numX; x++) {
for (let y = 0; y < _numY; y++) {
let above = y - 1;
let below = y + 1;
let left = x - 1;
let right = x + 1;
if (above < 0) {
above = _numY - 1;
}
if (below === _numY) {
below = 0;
}
if (left < 0) {
left = _numX - 1;
}
if (right === _numX) {
right = 0;
}
_cellArray[x][y].addNeighbour(_cellArray[left][above]);
_cellArray[x][y].addNeighbour(_cellArray[left][y]);
_cellArray[x][y].addNeighbour(_cellArray[left][below]);
_cellArray[x][y].addNeighbour(_cellArray[x][below]);
_cellArray[x][y].addNeighbour(_cellArray[right][below]);
_cellArray[x][y].addNeighbour(_cellArray[right][y]);
_cellArray[x][y].addNeighbour(_cellArray[right][above]);
_cellArray[x][y].addNeighbour(_cellArray[x][above]);
}
}
}
// ====== Cell Class ====== //
class Cell {
constructor (ex, why) { // constructor
this.x = ex * _cellSize;
this.y = why * _cellSize;
if (random(2) > 1) {
this.nextState = true;
} else {
this.nextState = false;
}
this.state = this.nextState;
this.neighbours = [];
}
addNeighbour (cell) {
this.neighbours.push(cell);
}
calcNextState () {
let liveCount = 0;
for (let i = 0; i < this.neighbours.length; i++) {
if (this.neighbours[i].state) {
liveCount++;
}
}
if (this.state) {
if ((liveCount === 2) || (liveCount === 3)) {
this.nextState = true;
} else {
this.nextState = false;
}
} else {
if (liveCount === 3) {
this.nextState = true;
} else {
this.nextState = false;
}
}
}
drawMe () {
this.state = this.nextState;
//stroke(0);
noStroke();
if (this.state) {
fill(0, 100);
} else {
fill(255);
}
circle(this.x, this.y, _cellSize);
}
}