Created
March 18, 2015 19:41
-
-
Save goldensunliu/865469b6f5a43779eb2e to your computer and use it in GitHub Desktop.
Game of life in Processing.js
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
// Game of Life | |
int sx, sy; | |
float density = 0.2; | |
int lifeSqureWidth = 3; | |
int[][][] world; | |
void populate() { | |
for (int i = 0; i < sx * sy * density; i++) { | |
world[(int)random(sx)][(int)random(sy)][1] = 1; | |
} | |
} | |
void setup() | |
{ | |
size(900, 900); | |
frameRate(12); | |
sx = width/lifeSqureWidth; | |
sy = height/lifeSqureWidth; | |
world = new int[sx][sy][2]; | |
stroke(255); | |
populate(); | |
} | |
void draw() | |
{ | |
background(0); | |
// Drawing and update cycle | |
for (int x = 0; x < sx; x=x+1) { | |
for (int y = 0; y < sy; y=y+1) { | |
//if (world[x][y][1] == 1) | |
// Change recommended by The.Lucky.Mutt | |
if ((world[x][y][1] == 1) || (world[x][y][1] == 0 && world[x][y][0] == 1)) | |
{ | |
world[x][y][0] = 1; | |
rect(x*lifeSqureWidth, y*lifeSqureWidth,1,1); | |
} | |
if (world[x][y][1] == -1) | |
{ | |
world[x][y][0] = 0; | |
} | |
world[x][y][1] = 0; | |
} | |
} | |
// Birth and death cycle | |
for (int x = 0; x < sx; x=x+1) { | |
for (int y = 0; y < sy; y=y+1) { | |
int count = neighbors(x, y); | |
if (count == 3 && world[x][y][0] == 0) | |
{ | |
world[x][y][1] = 1; | |
} | |
if ((count < 2 || count > 3) && world[x][y][0] == 1) | |
{ | |
world[x][y][1] = -1; | |
} | |
} | |
} | |
} | |
void mousePressed(){ | |
populate(); | |
} | |
// Count the number of adjacent cells 'on' | |
int neighbors(int x, int y) | |
{ | |
return world[(x + 1) % sx][y][0] + | |
world[x][(y + 1) % sy][0] + | |
world[(x + sx - 1) % sx][y][0] + | |
world[x][(y + sy - 1) % sy][0] + | |
world[(x + 1) % sx][(y + 1) % sy][0] + | |
world[(x + sx - 1) % sx][(y + 1) % sy][0] + | |
world[(x + sx - 1) % sx][(y + sy - 1) % sy][0] + | |
world[(x + 1) % sx][(y + sy - 1) % sy][0]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment