cau/rules.py
changeset 7 95ea605276a3
child 8 0db344245ac2
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/cau/rules.py	Thu Dec 30 18:31:19 2010 +0100
     1.3 @@ -0,0 +1,76 @@
     1.4 +import copy
     1.5 +from grid import Grid
     1.6 +
     1.7 +class Rule(object):
     1.8 +
     1.9 +	def iterate(self, oldgrid):
    1.10 +		grid = copy.deepcopy(oldgrid)
    1.11 +		for x in xrange(oldgrid.minx - 1, oldgrid.maxx + 2):
    1.12 +			for y in xrange(oldgrid.miny - 1, oldgrid.maxy + 2):
    1.13 +				#print x, y, self.neighbours(oldgrid, x, y)
    1.14 +				n = self.neighbours(oldgrid, (x, y))
    1.15 +				if n > 2:
    1.16 +					grid.set((x, y))					
    1.17 +		return grid
    1.18 +
    1.19 +	def neighbours(self, grid, (testx, testy)):
    1.20 +		n = 0
    1.21 +		#print "testing ", testx, testy
    1.22 +		for x in range(testx - 1, testx + 2):
    1.23 +			for y in range(testy - 1, testy + 2):
    1.24 +				if (x, y) in grid.cells:
    1.25 +					n += 1
    1.26 +				#print x, y, n
    1.27 +		return n 
    1.28 +	
    1.29 +
    1.30 +class Rule2(object):
    1.31 +
    1.32 +	def iterate(self, oldgrid):
    1.33 +		grid = copy.deepcopy(oldgrid)
    1.34 +		for x in xrange(oldgrid.minx - 1, oldgrid.maxx + 2):
    1.35 +			for y in xrange(oldgrid.miny, oldgrid.maxy + 2):
    1.36 +				#print "testing ", x, y,
    1.37 +				if (x+1, y) in oldgrid.cells or (x, y-1) in oldgrid.cells:
    1.38 +					grid.set((x, y), 1)								
    1.39 +		return grid
    1.40 +
    1.41 +import random
    1.42 +import marshal
    1.43 +
    1.44 +class PotentialGrowth(object):
    1.45 +		
    1.46 +	def __init__(self):
    1.47 +		random.seed()
    1.48 +
    1.49 +	def iterate(self, oldgrid):
    1.50 +		grid = oldgrid
    1.51 +		value_pos = {}
    1.52 +		for i in range(2, 5):
    1.53 +			if i in oldgrid.valuemap:
    1.54 +				value_pos[i] = copy.deepcopy(oldgrid.valuemap[i])
    1.55 +		for i in range(2, 5):
    1.56 +			if i in oldgrid.valuemap:
    1.57 +				for cell in value_pos[i]:
    1.58 +					pos = cell
    1.59 +					value = i
    1.60 +					new_pos, new_value = self.grow(grid, pos)
    1.61 +					grid.set(new_pos, new_value)
    1.62 +					grid.set(pos, value - 1)				
    1.63 +		return grid
    1.64 +
    1.65 +	def grow(self, grid, (x, y)):
    1.66 +		n1 = [(x-1, y), (x, y+1), (x+1, y), (x, y-1)]
    1.67 +		n2 = [(x+1, y+1), (x+1, y-1), (x-1, y-1), (x-1, y+1)]
    1.68 +		c0 = (n1, )
    1.69 +		c1 = (n1, n2)
    1.70 +		c2 = (n1, n1, n2)
    1.71 +		neighbours = random.choice(random.choice((c0, c1, c2)))
    1.72 +		neighbours = [n for n in neighbours if n not in grid.cells]
    1.73 +		if len(neighbours):
    1.74 +			pos = random.choice(neighbours)	
    1.75 +			value = 4
    1.76 +		else:
    1.77 +			pos = (x, y)
    1.78 +			value = grid.cells[pos]
    1.79 +		return pos, value