xxxxxxxxxx
Cell [][]_cellArray;
int _cellSize= 10;
int _numX, _numY;
void setup(){
size(500,300);
_numX = floor(width/_cellSize);
_numY = floor(height/ _cellSize);
frameRate(10);
restart();
}
void restart() {
_cellArray = new Cell[_numX][_numY]; // call celarray is wide x by high y
for(int x = 0; x< _numX; x++){
for (int y = 0; y< _numY; y++){
Cell newCell = new Cell(x,y);
_cellArray[x][y] = newCell;
}
}
// loop to tell each object is neighbour
for (int x =0; x< _numX; x++){
for( int y = 0; y < _numY; y++){
//gets locations for sides
int above =y-1;
int below = y+1;
int left = x-1;
int right = x +1;
//wraps the loctaions at sides
if (above< 0){above= _numY-1;}
if (below == _numY){below = 0;}
if (left < 0){left = _numX-1;}
if(right ==_numX){right =0;}
//pass refrences to sorrunding locations
_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]);
}
}
}
void draw(){
background(200);
for(int x = 0; x < _numX; x++){
for(int y = 0; y< _numY; y++){
_cellArray[x][y].calcNextState();
}
}
translate( _cellSize/2, -_cellSize/2);
for (int x =0; x<_numX;x++){
for(int y=0;y <_numY;y++) {
_cellArray[x][y].drawMe();
}
}
}
void mousePressed(){
restart();
}
//-----------------------object--------------------
class Cell{ // on or off
float x,y;
boolean state;
boolean nextState;
Cell[] neighbours;
// randomise intial state
Cell(float ex, float why){
x = ex*_cellSize;
y = why * _cellSize;
if (random(2)>1){
nextState = true;
} else{
nextState =false;
}
state = nextState;
neighbours = new Cell[0];
}
void addNeighbour(Cell cell){
neighbours = (Cell [])append(neighbours, cell);
}
void calcNextState(){
int liveCount = 0;
for(int i = 0; i < neighbours.length; i++){
if (neighbours[i].state == true){
liveCount++;
}
}
if (state == true) {
if((liveCount==2)|| (liveCount == 3)){
nextState = true;
} else {
nextState =false;
}
}else{
if (liveCount ==3){
nextState = true;
}else{
nextState = false;
}
}
}//end
void drawMe(){
state = nextState;
stroke(0);
if (state == true){
fill(0);
}else{
fill(255);
}
rect(x,y,_cellSize,_cellSize);
}
}