int N;
int C_SIZE = 10;
boolean[][] board = new boolean[N][N];
boolean paused = false;
void setup() {
size(500, 500);
N = width / C_SIZE;
board = new boolean[N][N];
initBoard();
frameRate(5);
stroke(255);
strokeWeight(2);
}
void draw() {
drawBoard();
if (!paused) {
updateBoard();
}
}
void keyPressed() {
if (key == 'r') {
initBoard();
}
if (key == ' ') {
paused = !paused;
}
}
void mousePressed() {
int r = mouseY / C_SIZE;
int c = mouseX / C_SIZE;
board[r][c] = !board[r][c];
}
void initBoard() {
for (int r = 0; r < N; r++) {
for (int c = 0; c < N; c++) {
board[r][c] = random(0, 1) < 0.5;
}
}
}
void drawBoard() {
for (int r = 0; r < N; r++) {
for (int c = 0; c < N; c++) {
if (board[r][c]) {
fill(0);
} else {
fill(255);
}
int x = c * C_SIZE;
int y = r * C_SIZE;
rect(x, y, C_SIZE, C_SIZE);
}
}
}
int countNeighbor(int i, int j) {
int count = 0;
for (int r = i-1; r <= i+1; r++) {
for (int c = j-1; c <= j+1; c++) {
if (0 <= r && r < N && 0 <= c && c < N && board[r][c]) {
count++;
}
}
}
if(board[i][j]) {
count--; // remove cell (i, j) from count
}
return count;
}
void updateBoard() {
boolean[][] newBoard = new boolean[N][N];
for (int r = 0; r < N; r++) {
for (int c = 0; c < N; c++) {
int count = countNeighbor(r, c);
newBoard[r][c] = board[r][c];
if (board[r][c]) {
if (count < 2 || count > 3) {
newBoard[r][c] = false;
}
} else {
if (count == 3) {
newBoard[r][c] = true;
}
}
}
}
board = newBoard;
}