xxxxxxxxxx
// in-class practice__Cellular Automata (CA)
// demo for autonomy in Pearson (2011)
// 20181213
// chun-ju, tai
var _cellArray = []; // this will be a 2D array
var _numX, _numY;
var _cellSize = 10;
function setup() {
createCanvas(windowWidth, windowHeight);
_numX = floor(width/_cellSize);
_numY = floor(height/_cellSize);
restart();
}
function draw() {
background(200);
for (var x = 0; x < _numX; x++) {
for (var y = 0; y < _numY; y++) {
_cellArray[x][y].drawMe();
}
}
}
function mousePressed() {
restart();
}
function restart() {
// first, create a grid of cells
for (var x = 0; x<_numX; x++) {
_cellArray[x] = [];
for (var y = 0; y<_numY; y++) {
var newCell = new Cell(x, y);
//_cellArray[x][y] = newCell;
_cellArray[x].push(newCell);
}
}
// setup the neighbors of each cell
for (var x = 0; x < _numX; x++) {
for (var y = 0; y < _numY; y++) {
var above = y-1;
var below = y+1;
var left = x-1;
var 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 ====== //
function Cell(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 = [];
}
Cell.prototype.addNeighbour = function(c) {
this.neighbours.push(c);
}
Cell.prototype.calcNextState = function() {
}
Cell.prototype.drawMe = function() {
this.state = this.nextState;
stroke(0);
if (this.state == true) {
fill(0, 100);
} else {
fill(255);
}
ellipse(this.x, this.y, _cellSize, _cellSize);
}