xxxxxxxxxx
// make accessible to DPD 2025: Complexity I
// schien@mail.ncku.edu.tw
// Cellular Automata (CA) in P5js
// demo for autonomy in Pearson (2011)
// trial 1: adding the concept of "strength"
// schien@mail.ncku.edu.tw, Spring 2023
let _cellArray = []; // this will be a 2D array
let _numX, _numY;
let _cellSize = 10;
function setup() {
createCanvas(500, 500);
//frameRate(4);
_numX = floor(width / _cellSize);
_numY = floor(height / _cellSize);
restart();
}
function draw() {
background(200);
for (let x = 0; x < _numX; x++) {
for (let y = 0; y < _numY; y++) {
_cellArray[x][y].calcNextState();
}
}
translate(_cellSize / 2, _cellSize / 2);
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] = [];
for (let y = 0; y < _numY; y++) {
let newCell = new Cell(x, y);
_cellArray[x].push(newCell);
}
}
// 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;
this.strength = 1;
} else {
this.nextState = false;
this.strength = 0;
}
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;
this.strength++;
} else {
this.nextState = false;
this.strength--;
}
} else {
if (liveCount === 3) {
this.nextState = true;
this.strength++;
} else {
this.nextState = false;
this.strength--;
}
}
if (this.strength < 0) {
this.strength = 0;
}
}
drawMe() {
this.state = this.nextState;
stroke(255);
fill(0, 50);
circle(this.x, this.y, _cellSize*this.strength);
}
}