コード
GOL gol;
void setup() {
size(960, 540);
colorMode(HSB, 360, 100, 100);
gol = new GOL();
}
void draw() {
background(0, 0, 100);
gol.generate();
gol.display();
if (frameCount%200 == 0) {
gol.init();
}
}
void mousePressed() {
gol.init();
}
class GOL {
int w = 20;
int columns, rows;
int[][] board;
GOL() {
columns = width / w;
rows = height / w;
board = new int[columns][rows];
init();
}
void init() {
for (int j = 0; j < rows; j++) {
for (int i = 0; i < columns; i++) {
board[i][j] = int(random(2));
}
}
}
void generate() {
int[][] next = new int[columns][rows];
for (int y = 1; y < rows -1; y++) {
for (int x = 1; x < columns -1; x++) {
int neighbors = 0;
for (int j = -1; j <= 1; j++) {
for (int i = -1; i <= 1; i++) {
neighbors += board[x+i][y+j];
}
}
neighbors -= board[x][y];
if ((board[x][y] == 1)&&(neighbors < 2)) {
next[x][y] = 0;
} else if ((board[x][y] == 1)&&(neighbors > 3)) {
next[x][y] = 0;
} else if ((board[x][y] == 0)&&(neighbors == 3)) {
next[x][y] = 1;
} else {
next[x][y] = board[x][y];
}
}
}
board = next;
}
int sum() {
int n = 0;
for (int y = 0; y < rows; y++) {
for (int x = 0; x < columns; x++) {
n += board[x][y];
}
}
return n;
}
void display() {
for (int j = 0; j < rows; j++) {
for (int i = 0; i < columns; i++) {
if (board[i][j] == 1) {
fill(330, 80, 100);
} else {
fill(0, 0, 80);
}
stroke(0, 0, 100);
strokeWeight(0.5);
rect(i*w, j*w, w, w);
}
}
}
}