Created
November 30, 2008 23:24
-
-
Save jyotty/30554 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Arrays; | |
import java.lang.Math; | |
boolean play = false; | |
int sx, sy; | |
int[][][] world; | |
float density = 0.5; | |
int drawState = 20; | |
int fr = 30; | |
int[] stayAlive = {2, 3}; | |
int[] comeToLife = {3, }; | |
void setup() { | |
size(601, 601, P2D); | |
frameRate(fr); | |
sx = width/5; | |
sy = height/5; | |
world = new int[sx][sy][2]; | |
} | |
void draw() { | |
background(0); | |
noStroke(); | |
for (int x = 0; x < sx; x++) { | |
for (int y = 0; y < sy; y++) { | |
fill((int)(Math.log((double)world[x][y][1]/20.0+1)*315), 10, 5); | |
rect(x*5+1, y*5+1, 4, 4); | |
world[x][y][0] = world[x][y][1]; | |
} | |
} | |
if (!play) return; | |
for (int x = 0; x < sx; x++) { | |
for (int y = 0; y < sy; y++) { | |
int count = neighbors(x,y); | |
if (world[x][y][0] == 0 && Arrays.binarySearch(comeToLife, count) >= 0) { | |
world[x][y][1] = 20; | |
} else if (world[x][y][0] > 0 && Arrays.binarySearch(stayAlive, count) >= 0) { | |
if (world[x][y][1] >= 2) world[x][y][1]--; | |
} else if (world[x][y][0] > 0) { | |
world[x][y][1] = 0; | |
} | |
} | |
} | |
} | |
// Count the number of adjacent world 'on' | |
int neighbors(int x, int y) { | |
int res = 0; | |
if (world[(x + 1) % sx][y][0] > 0) res++; | |
if (world[x][(y + 1) % sy][0] > 0) res++; | |
if (world[(x + sx - 1) % sx][y][0] > 0) res++; | |
if (world[x][(y + sy - 1) % sy][0] > 0) res++; | |
if (world[(x + 1) % sx][(y + 1) % sy][0] > 0) res++; | |
if (world[(x + sx - 1) % sx][(y + 1) % sy][0] > 0) res++; | |
if (world[(x + sx - 1) % sx][(y + sy - 1) % sy][0] > 0) res++; | |
if (world[(x + 1) % sx][(y + sy - 1) % sy][0] > 0) res++; | |
return res; | |
} | |
void keyPressed() { | |
switch (key) { | |
case 'r': setup(); randWorld(); break; | |
case 'c': setup(); play = false; break; | |
case ' ': play = !play; break; | |
case '-': if (fr > 6) {fr -= 6; frameRate(fr); } break; | |
case '=': if (fr < 30) {fr += 6; frameRate(fr); } break; | |
} | |
} | |
void mousePressed() { | |
int x = (mouseX-2)/5; | |
int y = (mouseY-3)/5; | |
drawState = world[x][y][1] > 0 ? 0 : 20; | |
world[x][y][1] = drawState; | |
} | |
void mouseDragged() { | |
int x = (mouseX-2)/5; | |
int y = (mouseY-3)/5; | |
world[x][y][1] = drawState; | |
} | |
void randWorld() { | |
// Set random world to 'on' | |
for (int i = 0; i < sx * sy * density; i++) { | |
world[(int)random(sx)][(int)random(sy)][1] = 20; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment