cau/rules.py
author Eugen Sawin <sawine@me73.com>
Thu, 30 Dec 2010 18:31:19 +0100
changeset 7 95ea605276a3
child 8 0db344245ac2
permissions -rw-r--r--
Moved cau to cau.
     1 import copy
     2 from grid import Grid
     3 
     4 class Rule(object):
     5 
     6 	def iterate(self, oldgrid):
     7 		grid = copy.deepcopy(oldgrid)
     8 		for x in xrange(oldgrid.minx - 1, oldgrid.maxx + 2):
     9 			for y in xrange(oldgrid.miny - 1, oldgrid.maxy + 2):
    10 				#print x, y, self.neighbours(oldgrid, x, y)
    11 				n = self.neighbours(oldgrid, (x, y))
    12 				if n > 2:
    13 					grid.set((x, y))					
    14 		return grid
    15 
    16 	def neighbours(self, grid, (testx, testy)):
    17 		n = 0
    18 		#print "testing ", testx, testy
    19 		for x in range(testx - 1, testx + 2):
    20 			for y in range(testy - 1, testy + 2):
    21 				if (x, y) in grid.cells:
    22 					n += 1
    23 				#print x, y, n
    24 		return n 
    25 	
    26 
    27 class Rule2(object):
    28 
    29 	def iterate(self, oldgrid):
    30 		grid = copy.deepcopy(oldgrid)
    31 		for x in xrange(oldgrid.minx - 1, oldgrid.maxx + 2):
    32 			for y in xrange(oldgrid.miny, oldgrid.maxy + 2):
    33 				#print "testing ", x, y,
    34 				if (x+1, y) in oldgrid.cells or (x, y-1) in oldgrid.cells:
    35 					grid.set((x, y), 1)								
    36 		return grid
    37 
    38 import random
    39 import marshal
    40 
    41 class PotentialGrowth(object):
    42 		
    43 	def __init__(self):
    44 		random.seed()
    45 
    46 	def iterate(self, oldgrid):
    47 		grid = oldgrid
    48 		value_pos = {}
    49 		for i in range(2, 5):
    50 			if i in oldgrid.valuemap:
    51 				value_pos[i] = copy.deepcopy(oldgrid.valuemap[i])
    52 		for i in range(2, 5):
    53 			if i in oldgrid.valuemap:
    54 				for cell in value_pos[i]:
    55 					pos = cell
    56 					value = i
    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 = 4
    73 		else:
    74 			pos = (x, y)
    75 			value = grid.cells[pos]
    76 		return pos, value