Hexagonal Life Game
@author
float e = 6.0;
int X = 50;
int Y = 50;
int[][] states;
void setup(){
size(640, 480);
frameRate(10);
stroke(30);
states = new int[X][Y];
for(int x = 0; x < X; x++){
for(int y = 0; y < Y; y++){
if(random(1) < 0.25){
states[x][y] = 1;
} else {
states[x][y] = 0;
}
}
}
}
void mousePressed(){
for(int x = 0; x < X; x++){
for(int y = 0; y < Y; y++){
if(random(1) < 0.25){
states[x][y] = 1;
} else {
states[x][y] = 0;
}
}
}
}
void draw(){
background(60);
float xStep = sqrt(3) * e;
float yStep = 3.0 / 2.0 * e;
float xStart = -(xStep * X + xStep / 2.0) / 2.0;
float yStart = -(yStep * (Y - 1) + yStep / 2.0) / 2.0;
translate(width / 2, height / 2);
for(int x = 0; x < X; x++){
for(int y = 0; y < Y; y++){
pushMatrix();
if(y % 2 == 0){
translate(x * xStep + xStart, y * yStep + yStart);
} else {
translate(x * xStep + xStep / 2.0 + xStart, y * yStep + yStart);
}
if(states[x][y] == 1){
fill(255, 140, 0);
} else {
fill(60);
}
beginShape();
for(float angle = 0.0; angle < 360; angle += 60){
float radian = radians(angle - 90);
vertex(e * cos(radian), e * sin(radian));
}
endShape(CLOSE);
popMatrix();
}
}
int[][] nextStates = new int[X][Y];
for(int x = 0; x < X; x++){
for(int y = 0; y < Y; y++){
int lifes = 0;
int up = y != 0 ? y - 1: Y - 1;
int down = y != Y - 1 ? y + 1: 0;
int left = x != 0 ? x - 1: X - 1;
int right = x != X - 1 ? x + 1: 0;
if(y % 2 == 0){
int diaLeft = x != 0 ? x - 1: X - 1;
int diaRight = x;
lifes = states[diaLeft][up] + states[diaRight][up] +
states[left][y] + states[right][y] +
states[diaLeft][down] + states[diaRight][down];
} else {
int diaLeft = x;
int diaRight = x != X - 1 ? x + 1: 0;
lifes = states[diaLeft][up] + states[diaRight][up] +
states[left][y] + states[right][y] +
states[diaLeft][down] + states[diaRight][down];
}
if(states[x][y] == 1){
if(2 <= lifes && lifes <= 4){
nextStates[x][y] = 1;
} else {
nextStates[x][y] = 0;
}
} else {
if(3 <= lifes && lifes <= 4){
nextStates[x][y] = 1;
} else {
nextStates[x][y] = 0;
}
}
}
}
states = nextStates;
}