cau/rules.py
author Eugen Sawin <sawine@me73.com>
Sun, 09 Jan 2011 16:22:27 +0100
changeset 9 355487ddb38a
parent 7 95ea605276a3
child 11 a131769728f1
permissions -rw-r--r--
Needs to be removed again.
     1 import copy
     2 from grid import Grid
     3 
     4 class Rule1(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 		self.potential = 4 # values 4-8 are viable
    46 
    47 	def iterate(self, oldgrid):
    48 		grid = oldgrid
    49 		value_pos = {}
    50 		for i in range(2, self.potential+1):
    51 			if i in oldgrid.valuemap:
    52 				value_pos[i] = copy.deepcopy(oldgrid.valuemap[i])
    53 		for value, cells in value_pos.iteritems():
    54 			for pos in cells:
    55 				new_pos, new_value = self.grow(grid, pos)
    56 				grid.set(new_pos, new_value)
    57 				grid.set(pos, value - 1)				
    58 		return grid
    59 
    60 	def grow(self, grid, (x, y)):
    61 		n1 = [(x-1, y), (x, y+1), (x+1, y), (x, y-1)]
    62 		n2 = [(x+1, y+1), (x+1, y-1), (x-1, y-1), (x-1, y+1)]
    63 		c0 = (n1, )
    64 		c1 = (n1, n2)
    65 		c2 = (n1, n1, n2)
    66 		neighbours = random.choice(random.choice((c0, c1, c2)))
    67 		neighbours = [n for n in neighbours if n not in grid.cells]
    68 		if len(neighbours):
    69 			pos = random.choice(neighbours)	
    70 			value = self.potential
    71 		else:
    72 			pos = (x, y)
    73 			value = grid.cells[pos]
    74 		return pos, value
    75 
    76