import pygame import random WIDTH = 640 #width of screen HEIGHT = 480 #height of screen LIFE_WIDTH=64 LIFE_HEIGHT=48 DENSITY = 0.5 def init_random_life_world(): new_life_world = [] for y in range(0, LIFE_HEIGHT): c_row = [] for x in range(0, LIFE_WIDTH): cur_random = random.random() if cur_random > DENSITY: c_row.append(1) else: c_row.append(0) new_life_world.append(c_row) return new_life_world def update_life_world(life_world_passed): new_life_world = [] for y in range(0, LIFE_HEIGHT): c_row = [] for x in range(0, LIFE_WIDTH): # get number of neighbors on in 8 surrounding cells number_on = life_world_passed[y][ (x-1)%LIFE_WIDTH ] + \ life_world_passed[y][ (x+1)%LIFE_WIDTH ] + \ life_world_passed[ (y-1)%LIFE_HEIGHT ][x] + \ life_world_passed[ (y+1)%LIFE_HEIGHT ][x] + \ life_world_passed[ (y-1)%LIFE_HEIGHT ][(x-1)%LIFE_WIDTH] + \ life_world_passed[ (y-1)%LIFE_HEIGHT ][(x+1)%LIFE_WIDTH] + \ life_world_passed[ (y+1)%LIFE_HEIGHT ][(x-1)%LIFE_WIDTH] + \ life_world_passed[ (y+1)%LIFE_HEIGHT ][(x+1)%LIFE_WIDTH] # RULES: # dead cell w/ 3 neighbors wakes up # live cell w/ 2 or 3 neighbors stays alive if (life_world_passed[y][x] == 0 and number_on == 3) or \ (life_world_passed[y][x] == 1 and number_on in (2,3) ): c_row.append(1) else: c_row.append(0) new_life_world.append(c_row) return new_life_world def show_life_world(life_world): for y in range(0, LIFE_HEIGHT): for x in range(0, LIFE_WIDTH): if life_world[y][x] == 1: color = (0, 255, 0) else: color = (0, 0, 0) pygame.draw.rect(screen, color, (x*10, y*10, 9, 9)) pygame.display.flip() screen = pygame.display.set_mode((WIDTH, HEIGHT)) #make screen life_world = init_random_life_world() for iteration in range(1, 10000): show_life_world(life_world) life_world = update_life_world(life_world) # print "GENERATION: ", iteration raw_input("DONE! Press any key to continue") pygame.display.quit()