Created
July 12, 2012 06:24
-
-
Save brianriley/3096249 to your computer and use it in GitHub Desktop.
Game of Life with cells colored based on their neighbor density
This file contains hidden or 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
int FRAME_RATE = 12; | |
int CELL_SIZE = 5; | |
int PIXEL_WIDTH = 1400; | |
int PIXEL_HEIGHT = 800; | |
float INITIAL_POPULATION_DENSITY = 0.5; | |
// white (neighbor density = 8), yellow (neighbor density = 7), orange (neighbor density = 6), red (neighbor density = 5), purple (neightbor density = 4), blue (neighbor density < 4) | |
color[] colors = {color(255,255,255), color(255,255,0), color(255,166,0), color(255, 0, 0), color(255,0,255), color(0,0,255)}; | |
int WORLD_WIDTH = PIXEL_WIDTH/CELL_SIZE; | |
int WORLD_HEIGHT = PIXEL_HEIGHT/CELL_SIZE; | |
int[][] world; | |
void setup() { | |
size(PIXEL_WIDTH, PIXEL_HEIGHT); | |
frameRate(FRAME_RATE); | |
world = new int[WORLD_WIDTH][WORLD_HEIGHT]; | |
for (int i=0; i<WORLD_WIDTH * WORLD_HEIGHT * INITIAL_POPULATION_DENSITY; i++) { | |
world[(int)random(WORLD_WIDTH)][(int)random(WORLD_HEIGHT)] = 1; | |
} | |
} | |
void draw() { | |
background(0); | |
evolve(); | |
draw_world(); | |
} | |
void evolve() { | |
int[][] new_world = new int[WORLD_WIDTH][WORLD_HEIGHT]; | |
for (int x=1; x<WORLD_WIDTH-1; x++) { | |
for (int y=1; y<WORLD_HEIGHT-1; y++) { | |
// add up the neighbers from top left, clockwise | |
int neighbors = neighbor_count(world, x, y); | |
boolean empty = world[x][y] == 0; | |
int alive = 0; | |
if (!empty) { | |
if (neighbors < 2) { | |
alive = 0; | |
} else if (neighbors <= 3) { | |
alive = 1; | |
} else { | |
alive = 0; | |
} | |
} else { | |
if (neighbors == 3) { | |
alive = 1; | |
} | |
} | |
new_world[x][y] = alive; | |
} | |
} | |
arrayCopy(new_world, world); | |
} | |
int neighbor_count(int[][] world, int x, int y) { | |
int neighbors = world[x-1][y-1] + | |
world[x][y-1] + | |
world[x+1][y-1] + | |
world[x-1][y] + | |
world[x+1][y] + | |
world[x-1][y+1] + | |
world[x][y+1] + | |
world[x+1][y+1]; | |
return neighbors; | |
} | |
void draw_world() { | |
for (int x=0; x<WORLD_WIDTH; x++) { | |
for (int y=0; y<WORLD_HEIGHT; y++) { | |
if (world[x][y] == 1) { | |
int neighbors = neighbor_count(world, x, y); | |
if (neighbors == 8) { | |
fill(colors[0]); | |
} else if (neighbors == 7) { | |
fill(colors[1]); | |
} else if (neighbors == 6) { | |
fill(colors[2]); | |
} else if (neighbors == 5) { | |
fill(colors[3]); | |
} else if (neighbors == 4) { | |
fill(colors[4]); | |
} else { | |
fill(colors[5]); | |
} | |
} else { | |
fill(0); | |
} | |
rect(x*CELL_SIZE, y*CELL_SIZE, CELL_SIZE, CELL_SIZE); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment