2020-05-07_life-with-class.html


001| #:name::Life With Class
002| #:link::https://thehardcorecoder.com/2020/05/07/life-with-class/
003| #:date::2020-05-07
004| #:code::
005| life = ConwayLife((640,480), (5,5), fpath=ImgFrmsPath)
006| 
007| life.go(2000, percentage=0.18)
008| 
009| #:code::
010| class ConwayLife (object):
011| 
012|     def __init__ (self, dims, cell=(4,4), **kwargs):
013|         self.dims = dims
014|         self.cell = cell
015|         self.fname = 'life-%05d.png'  # kwarg
016|         self.fpath = BasePath         # kwarg
017|         self.fmode = 'PNG'            # kwarg
018|         self.cols =  self.dims[0]//self.cell[0]
019|         self.rows =  self.dims[1]//self.cell[1]
020|         self.buf1 = None
021|         self.buf2 = None
022|         self.colors = ConwayLife.colorlist(LifeColors)
023| 
024|     def go (self, cycles=20, percentage=0.5):
025|         # Clear buffers to zero...
026|         self.buf1 = [[0 for c in range(self.cols)] for r in range(self.rows)]
027|         self.buf2 = [[0 for c in range(self.cols)] for r in range(self.rows)]
028| 
029|         # Initialize buffers with some life...
030|         for r in range(self.rows):
031|             for c in range(self.cols):
032|                 self.buf1[r][c] = (1 if random() < percentage else 0)
033| 
034|         # Cycle the life...
035|         for n in range(cycles):
036|             self._life_cycle()
037|             self._save_frame(n)
038| 
039| #:code::
040|     def _life_cycle (self):
041|         # For each row and column...
042|         for r in range(self.rows):
043|             for c in range(self.cols):
044|                 # Do the neighbor counts...
045|                 self._count_neighbors(r,c)
046| 
047|         # For each row and column...
048|         for r in range(self.rows):
049|             for c in range(self.cols):
050|                 # Apply the counts per the rules...
051|                 self._apply_rule(r,c)
052| 
053|     def _save_frame (self, frm_nbr):
054|         filename = path.join(self.fpath, self.fname % frm_nbr)
055|         dims = (self.cols*self.cell[0], self.rows*self.cell[1])
056| 
057|         # Create image...
058|         im = Image.new('RGB', dims, (255,255,255))
059|         draw = ImageDraw.Draw(im)
060| 
061|         # For each row...
062|         for y in range(self.rows):
063|             # For each column...
064|             for x in range(self.cols):
065|                 # Get the cell value and color...
066|                 v = self.buf1[y][x]
067|                 c = self.colors(v)
068|                 # Calculate cell's ULC...
069|                 x0 = x * self.cell[0]
070|                 y0 = y * self.cell[1]
071|                 # Draw the cell...
072|                 for yy in range(self.cell[1]):
073|                     for xx in range(self.cell[0]):
074|                         draw.point((x0+xx,y0+yy), fill=c)
075| 
076|         # Save the image...
077|         im.save(filename, self.fmode)
078|         return filename
079| 
080| #:code::
081|     def _count_neighbors (self, row, col):
082|         total = 0
083|         left = (self.cols-1) if col == 0 else (col-1)
084|         right = (col+1) if col < (self.cols-1) else 0
085|         top = (self.rows-1) if row == 0 else (row-1)
086|         bot = (row+1) if row < (self.rows-1) else 0
087| 
088|         # Top row...
089|         total += (1 if (0 < self.buf1[top][left] ) else 0)
090|         total += (1 if (0 < self.buf1[top][col]  ) else 0)
091|         total += (1 if (0 < self.buf1[top][right]) else 0)
092| 
093|         # Middle row...
094|         total += (1 if (0 < self.buf1[row][left] ) else 0)
095|         total += (1 if (0 < self.buf1[row][right]) else 0)
096| 
097|         # Bottom row...
098|         total += (1 if (0 < self.buf1[bot][left] ) else 0)
099|         total += (1 if (0 < self.buf1[bot][col]  ) else 0)
100|         total += (1 if (0 < self.buf1[bot][right]) else 0)
101| 
102|         # Save total in count(r,c)...
103|         self.buf2[row][col] = total
104|         return total
105| 
106|     def _apply_rule (self, row, col):
107|         age = self.buf1[row][col]  # cell age
108|         non = self.buf2[row][col]  # number of neighbors
109|         self.buf1[row][col] = self._rule(age, non)
110| 
111|     def _rule (self, age, neighbors):
112|         if 0 < age:
113|             # Cell is alive (needs 2 or 3 to survive)...
114|             return ((age+1) if (neighbors in [2,3]) else 0)
115| 
116|         # Cell is dead (needs 3 to spawn)...
117|         return (1 if neighbors == 3 else 0)
118| 
119| #:code::
120| LifeColors = [
121|     ( 1, (0x00,0x00,0x00)), # Dead cell
122|     ( 1, (0xff,0xff,0xff)), # Born cell
123|     ( 2, (0xff,0xff,0xbf)), # Live cell aging...
124|     ( 3, (0xff,0xff,0x7f)),
125|     ( 4, (0xff,0xff,0x3f)),
126|     ( 5, (0xff,0xff,0x00)),
127|     ( 6, (0xbf,0xff,0x00)),
128|     ( 7, (0x7f,0xff,0x00)),
129|     ( 8, (0x3f,0xff,0x00)),
130|     ( 9, (0x00,0xff,0x00)),
131|     (10, (0x00,0xbf,0x3f)),
132|     (20, (0x00,0x7f,0x7f)),
133|     ( 0, (0x00,0x3f,0x7f)),
134| ]
135| 
136| class colorlist (object):
137|     def __init__ (self, list_of_colors):
138|         self._cs = []
139|         cc = 0
140| 
141|         for entry in list_of_colors:
142|             self._cs.append((cc, entry[1]))
143|             cc += entry[0]
144| 
145|     def __call__ (self, age):
146|         t = [c[1] for c in self._cs if c[0] <= age]
147|         return t[-1]
148| 
149|     def __len__ (self): return len(self._cs)
150| 
151|     def __getitem__ (self, ix): return self._cs[ix]
152| 
153| #:end:code::
154|