Skip to content

Instantly share code, notes, and snippets.

@annahri
Created January 29, 2018 08:43
Show Gist options
  • Save annahri/c0b9d732c6dbcc73752820bbafe97c89 to your computer and use it in GitHub Desktop.
Save annahri/c0b9d732c6dbcc73752820bbafe97c89 to your computer and use it in GitHub Desktop.
Game of life in Processing
class Cell {
float x;
float y;
float size;
int state;
public Cell(float x, float y, float size) {
this.x = x;
this.y = y;
this.size = size;
}
void Draw() {
if (this.state == 1) {
fill(10,10,10);
} else {
fill(255);
}
noStroke();
rect(this.x, this.y, this.size, this.size);
}
}
Cell[][] cells;
int res = 5;
int rows;
int cols;
int offset = 1;
void setup() {
size(1000, 500);
rows = height / res;
cols = width / res;
cells = new Cell[rows][cols];
Generate(cells);
Randomize(cells);
}
void draw() {
DrawCell(cells);
Update();
}
void DrawCell(Cell[][] cell) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cell[i][j].Draw();
}
}
}
void Generate(Cell[][] cell) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
float x = j * res;
float y = i * res;
float s = res - offset;
cell[i][j] = new Cell(x, y, s);
}
}
}
void Update() {
Cell[][] newCells = new Cell[rows][cols];
Generate(newCells);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
int state = cells[i][j].state;
int neighbors = CountNeighbors(i, j, cells);
if (state == 0 && neighbors == 3) {
newCells[i][j].state = 1;
} else if (state == 1 && (neighbors < 2 || neighbors > 3)) {
newCells[i][j].state = 0;
} else {
newCells[i][j].state = state;
}
}
}
cells = newCells;
}
int CountNeighbors(int x, int y, Cell[][] cell) {
int count = 0;
for (int i = -1; i < 2; i++) {
for(int j = -1; j < 2; j++) {
try {
if (cell[i + x][j + y].state == 1) {
count++;
}
} catch (ArrayIndexOutOfBoundsException e) {
continue;
}
}
}
count -= cell[x][y].state;
return count;
}
void Randomize(Cell[][] cell) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cell[i][j].state = floor(random(2));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment