cau/rules.py
author Eugen Sawin <sawine@me73.com>
Mon, 18 Jul 2011 00:51:04 +0200
changeset 11 a131769728f1
parent 8 0db344245ac2
permissions -rw-r--r--
Added header.
     1 """
     2 Description: Circular cellular growth rules.
     3 Author: Eugen Sawin <sawine@me73.com>
     4 """
     5 
     6 import copy
     7 from grid import Grid
     8 
     9 class Rule1(object):
    10 	def iterate(self, oldgrid):
    11 		grid = copy.deepcopy(oldgrid)
    12 		for x in xrange(oldgrid.minx - 1, oldgrid.maxx + 2):
    13 			for y in xrange(oldgrid.miny - 1, oldgrid.maxy + 2):
    14 				#print x, y, self.neighbours(oldgrid, x, y)
    15 				n = self.neighbours(oldgrid, (x, y))
    16 				if n > 2:
    17 					grid.set((x, y))					
    18 		return grid
    19 
    20 	def neighbours(self, grid, (testx, testy)):
    21 		n = 0
    22 		#print "testing ", testx, testy
    23 		for x in range(testx - 1, testx + 2):
    24 			for y in range(testy - 1, testy + 2):
    25 				if (x, y) in grid.cells:
    26 					n += 1
    27 				#print x, y, n
    28 		return n 
    29 	
    30 
    31 class Rule2(object):
    32 	def iterate(self, oldgrid):
    33 		grid = copy.deepcopy(oldgrid)
    34 		for x in xrange(oldgrid.minx - 1, oldgrid.maxx + 2):
    35 			for y in xrange(oldgrid.miny, oldgrid.maxy + 2):
    36 				#print "testing ", x, y,
    37 				if (x+1, y) in oldgrid.cells or (x, y-1) in oldgrid.cells:
    38 					grid.set((x, y), 1)								
    39 		return grid
    40 
    41 import random
    42 import marshal
    43 
    44 class PotentialGrowth(object):		
    45 	def __init__(self):
    46 		random.seed()
    47 		self.potential = 4 # values 4-8 are viable
    48 
    49 	def iterate(self, oldgrid):
    50 		grid = oldgrid
    51 		value_pos = {}
    52 		for i in range(2, self.potential+1):
    53 			if i in oldgrid.valuemap:
    54 				value_pos[i] = copy.deepcopy(oldgrid.valuemap[i])
    55 		for value, cells in value_pos.iteritems():
    56 			for pos in cells:
    57 				new_pos, new_value = self.grow(grid, pos)
    58 				grid.set(new_pos, new_value)
    59 				grid.set(pos, value - 1)				
    60 		return grid
    61 
    62 	def grow(self, grid, (x, y)):
    63 		n1 = [(x-1, y), (x, y+1), (x+1, y), (x, y-1)]
    64 		n2 = [(x+1, y+1), (x+1, y-1), (x-1, y-1), (x-1, y+1)]
    65 		c0 = (n1, )
    66 		c1 = (n1, n2)
    67 		c2 = (n1, n1, n2)
    68 		neighbours = random.choice(random.choice((c0, c1, c2)))
    69 		neighbours = [n for n in neighbours if n not in grid.cells]
    70 		if len(neighbours):
    71 			pos = random.choice(neighbours)	
    72 			value = self.potential
    73 		else:
    74 			pos = (x, y)
    75 			value = grid.cells[pos]
    76 		return pos, value
    77 
    78