caumat.py
changeset 5 dd036093fc09
parent 4 20edf3e369a2
child 6 cac4ae0f22f4
     1.1 --- a/caumat.py	Thu Dec 30 14:36:25 2010 +0100
     1.2 +++ b/caumat.py	Thu Dec 30 15:19:36 2010 +0100
     1.3 @@ -44,20 +44,25 @@
     1.4  		random.seed()
     1.5  
     1.6  	def iterate(self, oldgrid):
     1.7 -		grid = copy.deepcopy(oldgrid)
     1.8 -		for cell in oldgrid.cells.iteritems():
     1.9 -			pos = cell[0]
    1.10 -			value = cell[1]
    1.11 -			if value > 1:
    1.12 -				new_pos, new_value = self.grow(grid, pos)
    1.13 -				grid.set(new_pos, new_value)
    1.14 -				grid.set(pos, value - 1)
    1.15 +		grid = oldgrid
    1.16 +		value_pos = {}
    1.17 +		for i in range(2, 5):
    1.18 +			if i in oldgrid.valuemap:
    1.19 +				value_pos[i] = copy.deepcopy(oldgrid.valuemap[i])
    1.20 +		for i in range(2, 5):
    1.21 +			if i in oldgrid.valuemap:
    1.22 +				for cell in value_pos[i]:
    1.23 +					pos = cell
    1.24 +					value = i
    1.25 +					new_pos, new_value = self.grow(grid, pos)
    1.26 +					grid.set(new_pos, new_value)
    1.27 +					grid.set(pos, value - 1)				
    1.28  		return grid
    1.29  
    1.30  	def grow(self, grid, (x, y)):
    1.31  		n1 = [(x-1, y), (x, y+1), (x+1, y), (x, y-1)]
    1.32  		n2 = [(x+1, y+1), (x+1, y-1), (x-1, y-1), (x-1, y+1)]
    1.33 -		neighbours = random.choice((n1, n1, n2))
    1.34 +		neighbours = random.choice((n1, n1, n1, n1, n1, n1, n2, n2, n2))
    1.35  		neighbours = [n for n in neighbours if n not in grid.cells]
    1.36  		if len(neighbours):
    1.37  			pos = random.choice(neighbours)	
    1.38 @@ -116,13 +121,15 @@
    1.39  	grid.set((0, 0), 4)
    1.40  
    1.41  	iterations = int(sys.argv[1])
    1.42 -
    1.43 +	last_pi = 3.0
    1.44  	for i in range(iterations):
    1.45  		A = len(grid)
    1.46  		r = grid.width() / 4.0 + grid.height() / 4.0
    1.47  		r_ideal = math.sqrt(A / math.pi)
    1.48  		A_ideal = r**2 * math.pi
    1.49  		pi = A / r**2
    1.50 +		pi = (pi + last_pi) / 2.0
    1.51 +		last_pi = pi
    1.52  		print "%i %f(%f) %i(%i) %f" % (i, r, r - r_ideal, 
    1.53  										A, A - A_ideal, pi)
    1.54