import controlP5.*;
ControlP5 controlP5;
int playerScale = 10;
int cols = 80;
int rows = 55;
int[][] world = new int[cols][rows];
int aliveFill = 128;
int backgroundFill = 0;
int systemReset = 0;
Knob speedKnob;
void setup() {
size(800,600);
smooth();
frameRate(10);
background(0);
translate(5,5);
controlP5 = new ControlP5(this);
controlP5.addButton("reset",10,-5,560,80,20).setId(1);
speedKnob = controlP5.addKnob("speed",1,30,10,100,560,20);
randomizeBoard();
}
void draw () {
translate(5,5);
if (systemReset == 1) {
systemReset = 0;
randomizeBoard();
}
int num;
for (int x=0; x < cols; x++) {
for (int y=0; y < rows; y++) {
num = checkNeighbours(x,y);
if (world[x][y] == 0 && num == 3) {
world[x][y] = 8;
drawCell(x, y, 1);
}
if ( world[x][y] == 1 && (num < 2 || num > 3) ) {
world[x][y] = -1;
drawCell(x, y, 0);
}
}
}
for (int x=0; x < cols; x++) {
for (int y=0; y < rows; y++) {
if (world[x][y] == 8)
world[x][y] = 1;
if (world[x][y] == -1)
world[x][y] = 0;
}
}
}
void reset(float theValue) {
println("a button event. "+theValue);
systemReset =1;
}
void drawCell(int x, int y, int alive) {
if (alive == 1) {
fill(aliveFill);
ellipse(x*playerScale, y*playerScale, 8, 8);
} else {
fill(backgroundFill);
noSmooth();
ellipse(x*playerScale, y*playerScale, 8, 8);
smooth();
}
}
int checkNeighbours(int x, int y) {
int neighbours = 0;
for (int dx=-1; dx<=1; dx++) {
for (int dy=-1; dy<=1; dy++) {
if (dy==0 && dx==0)
continue;
if ((x+dx >= 0 && x+dx < cols) && (y+dy >= 0 && y+dy < rows) && (world[x+dx][y+dy] == 1 || world[x+dx][y+dy] == -1) ) {
neighbours++;
}
}
}
return neighbours;
}
void randomizeBoard() {
for (int x=0; x < cols; x++) {
for (int y=0; y < rows; y++) {
world[x][y] = int(random(2));
if (world[x][y] == 1) {
drawCell(x, y, 1);
} else {
drawCell(x, y, 0);
}
}
}
}
void speed(int value) {
frameRate(value);
}