Game of Life
https://gyazo.com/9277eafc63919050acbb9261739058fd
code:java
Cell[][] _cellArray;
int _cellSize = 10;
int _numx, _numy;
void setup() {
size(500, 300);
_numx = floor(width/_cellSize);
_numy = floor(height/_cellSize);
restart();
}
void restart() {
for (int x = 0; x < _numx; x++) {
for (int y = 0; y < _numy; y++) {
Cell newCell = new Cell(x, y);
}
}
for (int x = 0; x < _numx; x++) {
for (int y = 0; y < _numy; y++) {
int above = y-1;
int below = y+1;
int left = x-1;
int 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; }
_cellArrayxy.addNeighbour(_cellArraylefty); _cellArrayxy.addNeighbour(_cellArrayxabove); _cellArrayxy.addNeighbour(_cellArrayxbelow); _cellArrayxy.addNeighbour(_cellArrayrighty); }
}
}
void draw() {
background(200);
for (int x = 0; x < _numx; x++) {
for (int y = 0; y < _numy; y++) {
_cellArrayxy.calcNextState(); }
}
translate(_cellSize/2, _cellSize/2);
for (int x = 0; x < _numx; x++) {
for (int y = 0; y < _numy; y++) {
}
}
saveFrame("###.jpg");
}
void mousePressed() {
restart();
}
class Cell {
float x, y;
boolean state;
boolean nextState;
Cell[] neighbors;
Cell(float ex, float why) {
x = ex * _cellSize;
y = why * _cellSize;
if (random(2) > 1) {
nextState = true;
} else {
nextState = false;
}
state = nextState;
}
void addNeighbour(Cell cell) {
neighbors = (Cell[])append(neighbors, cell);
}
void calcNextState() {
int liveCount = 0;
for (int i = 0; i < neighbors.length; i++) {
if (neighborsi.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;
}
}
}
void drawMe() {
state = nextState;
stroke(0);
if (state == true) {
fill(0);
} else {
fill(255);
}
ellipse(x, y, _cellSize, _cellSize);
}
}