#!/usr/bin/env python
# MINI PYGOL - Game of Life - Nico Nabholz (nico@nabholz.org)

gen = 1
cell = {}
import sys, os, random, time
os.system('clear')

rows, columns = os.popen('stty size', 'r').read().split()
y = int(rows) - 2
x = int(columns)

while 1:
    print chr(27) + "[H" + "Game Of Life (Generation: %d)" % gen
    for r in range(y):
        for c in range(x):
            if (r * c == 0 or r == y-1 or c == x-1): cell[c, r, gen] = 0
            elif gen == 1: cell[c, r, gen] = int(round(random.randrange(0,4,1)/3))
            else:
                homies = (cell[c-1, r-1, gen-1] + cell[c,   r-1, gen-1] + cell[c+1, r-1, gen-1] +
                          cell[c-1, r,   gen-1] + cell[c+1, r,   gen-1] +
                          cell[c-1, r+1, gen-1] + cell[c,   r+1, gen-1] + cell[c+1, r+1, gen-1])
                if (cell[c, r, gen-1] == 0 and homies == 3): cell[c, r, gen] = 1
                elif (cell[c, r, gen-1] == 1 and (homies == 2 or homies == 3)): cell[c, r, gen] = 1
                else: cell[c, r, gen] = 0
            if cell[c, r, gen] == 1: sys.stdout.write('O')
            else: sys.stdout.write(' ')
        print
    time.sleep(.1)
    gen += 1
