Mercurial > public > think_complexity
comparison Life.py @ 48:98eb01502cf5 tip
Follow up to last commit. Re-orient the r-pentomino. Added progress display.
author | Brian Neal <bgneal@gmail.com> |
---|---|
date | Wed, 31 Jul 2013 20:37:12 -0500 |
parents | 2b0e229e163c |
children |
comparison
equal
deleted
inserted
replaced
47:2b0e229e163c | 48:98eb01502cf5 |
---|---|
23 """Implements Conway's Game of Life. | 23 """Implements Conway's Game of Life. |
24 | 24 |
25 n: the number of rows and columns | 25 n: the number of rows and columns |
26 """ | 26 """ |
27 | 27 |
28 def __init__(self, n, mode='wrap', cval=0.0, random=False): | 28 def __init__(self, n, mode='wrap', cval=0.0, random=False, |
29 show_progress=None): | |
29 """Attributes: | 30 """Attributes: |
30 n: number of rows and columns | 31 n: number of rows and columns |
31 mode: how border conditions are handled | 32 mode: how border conditions are handled |
32 array: the numpy array that contains the data. | 33 array: the numpy array that contains the data. |
33 weights: the kernel used for convolution | 34 weights: the kernel used for convolution |
34 """ | 35 """ |
35 self.n = n | 36 self.n = n |
36 self.mode = mode | 37 self.mode = mode |
37 self.cval = cval | 38 self.cval = cval |
39 self.show_progress = show_progress | |
40 self.steps = 0 | |
41 | |
38 if random: | 42 if random: |
39 self.array = numpy.random.random_integers(0, 1, (n, n)) | 43 self.array = numpy.random.random_integers(0, 1, (n, n)) |
40 else: | 44 else: |
41 self.array = numpy.zeros((n, n), numpy.int8) | 45 self.array = numpy.zeros((n, n), numpy.int8) |
42 | 46 |
49 for i, j in coords: | 53 for i, j in coords: |
50 self.array[x+i, y+j] = 1 | 54 self.array[x+i, y+j] = 1 |
51 | 55 |
52 def loop(self, steps=1): | 56 def loop(self, steps=1): |
53 """Executes the given number of time steps.""" | 57 """Executes the given number of time steps.""" |
54 [self.step() for i in xrange(steps)] | 58 for i in xrange(steps): |
59 self.step() | |
55 | 60 |
56 def step(self): | 61 def step(self): |
57 """Executes one time step.""" | 62 """Executes one time step.""" |
58 con = scipy.ndimage.filters.convolve(self.array, | 63 con = scipy.ndimage.filters.convolve(self.array, |
59 self.weights, | 64 self.weights, |
60 mode=self.mode, | 65 mode=self.mode, |
61 cval=self.cval) | 66 cval=self.cval) |
62 | 67 |
63 boolean = (con==3) | (con==12) | (con==13) | 68 boolean = (con==3) | (con==12) | (con==13) |
64 self.array = numpy.int8(boolean) | 69 self.array = numpy.int8(boolean) |
70 | |
71 self.steps += 1 | |
72 if self.show_progress and self.steps % self.show_progress == 0: | |
73 print self.steps | |
65 | 74 |
66 | 75 |
67 class LifeViewer(object): | 76 class LifeViewer(object): |
68 """Generates an animated view of the grid.""" | 77 """Generates an animated view of the grid.""" |
69 def __init__(self, life, cmap=matplotlib.cm.gray_r, delay=1000): | 78 def __init__(self, life, cmap=matplotlib.cm.gray_r, delay=1000): |