#!/local/bin/python
from whrandom import randint
from time import sleep
from curses import *
class cell:
	cellx=celly=0
	def __init__(self,x,y):
		self.alive=self.new=0
		self.x=x
		self.y=y
		self.n=self.ne=self.nw=self.w=self.e=self.sw=self.se=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
		return(self.new)
	def regenx(self):
		self.alive=self.new
class life:
	def __init__(self,x,y,fill):
		self.U=range(x*y)
		for i in range(x):
			for j in range(y):
				k=i*y+j
				self.U[k]=cell(i,j)
		self.U[0].setxy(x,y)
		for i in self.U:
			i.map(self.U)
			i.reinit(fill)
		initscr()
		self.scr=newwin(0,0)
	def p(self,nalive):
		self.scr.move(0,0)
		for i in self.U:	self.scr.addch(i.p())
		self.scr.addstr('number alive =')
		self.scr.addstr('%d '%nalive)
		self.scr.refresh()
	def xit(self):
		endwin()
	def regen(self):
		j=0
		for i in self.U: j=j+i.regen()
		for i in self.U: i.regenx()
		self.p(j)
		sleep(1)
def main():
	l=life(23,80,10)
	l.p(0)
	sleep(1)
	try:
		while(1):	l.regen()
	except KeyboardInterrupt:
		l.xit()
if __name__ == '__main__': main()

