#!/local/bin/python
from time import sleep
from whrandom import randint
from curses import *
class cell:
	cellx=0
	celly=0
	def __init__(self,x,y,z):
		self.alive=0
		self.new=0
		self.x=x
		self.y=y
		self.z=z
		self.ne=0
		self.n=0
		self.nw=0
		self.w=0
		self.sw=0
		self.s=0
		self.se=0
		self.e=0
	def setxy(self,x,y):
		global cellx,celly
		cellx=x
		celly=y
	def map(self,U):
		global cellx,celly
		nx=(self.x+cellx-1)%cellx
		sx=(self.x+1)%cellx
		wy=(self.y+celly-1)%celly
		ey=(self.y+1)%celly
		self.w=U[(self.x*celly)+wy]
		self.e=U[(self.x*celly)+ey]
		self.n=U[(nx*celly)+self.y]
		self.s=U[(sx*celly)+self.y]
		self.nw=U[(nx*celly)+wy]
		self.ne=U[(nx*celly)+ey]
		self.sw=U[(sx*celly)+wy]
		self.se=U[(sx*celly)+ey]
	def reinit(self,rate):
		i=randint(0,100)
		if i < rate :	self.alive=1
		else:		self.alive=0
	def p(self):
		if self.alive == 1:	return 42
		else:			return 32
	def regen(self):
		i=self.nw.alive+self.n.alive+self.ne.alive
		i=i+self.w.alive+self.e.alive
		i=i+self.sw.alive+self.s.alive+self.se.alive
		if i==3 or (i==2 and self.alive==1): self.new=1
		else:		self.new=0
	def regenx(self):
		self.alive=self.new
class life:
	def __init__(self,x,y,fill):
		self.U=range(x*y)
		print "generating cells"
		for i in range(x):
			for j in range(y):
				k=i*y+j
				self.U[k]=cell(i,j,k)
		self.U[0].setxy(x,y)
		print "initializing links and fill"
		for i in range(len(self.U)):
			self.U[i].map(self.U)
			self.U[i].reinit(fill)
		initscr()
		self.scr=newwin(0,0)
	def myprint(self):
		self.scr.move(0,0)
		for i in range(len(self.U)):
			self.scr.addch(self.U[i].p())
		self.scr.refresh()
	def regen(self):
		for i in range(len(self.U)):
			self.U[i].regen()
		for i in range(len(self.U)):
			self.U[i].regenx()
		self.myprint()
	def xit(self):
		endwin()
def main():
	l=life(23,80,50)
	l.myprint()
	try:
		while(1):
			sleep(1)
			l.regen()
	except KeyboardInterrupt:
			l.xit()
if __name__ == '__main__': main()
