conway_life.html


001| '''John Conway's Game of Life.
001| 
001| Classes:
001|     ConwayLife  (dims, cell-dims, fname, fpath, fmode)
001| 
001| Functions:
001|     get_life_pattern(patt)  - takes a list of plaintext lines
001| 
001| Data:
001|     LifeColors          - default color scheme
001|     StartOptions        - configuration database
001|     Glider              - pattern
001|     GliderGun           - pattern
001|     TitleLife           - pattern
001|     TitleJohnConway     - pattern
001| 
001| '''

002| ####################################################################################################
003| from os import path
004| from time import perf_counter
005| from random import random
006| from PIL import Image, ImageDraw
007| from goodies import KWARG
008| ####################################################################################################
009| 
010| ##------------------------------------------------------------------------------------------------##
011| LifeColors = [
012|     ( 1, (0x00,0x00,0x00)), # Dead cell
013|     ( 1, (0xff,0xff,0xff)), # Born cell
014|     ( 2, (0xff,0xff,0xbf)), # Live cell aging...
015|     ( 4, (0xff,0xff,0x7f)),
016|     ( 6, (0xff,0xff,0x3f)),
017|     ( 8, (0xff,0xff,0x00)),
018|     (10, (0xbf,0xff,0x00)),
019|     (15, (0x7f,0xff,0x00)),
020|     (20, (0x3f,0xff,0x00)),
021|     (30, (0x00,0xff,0x00)),
022|     (40, (0x00,0xbf,0x3f)),
023|     (50, (0x00,0x7f,0x7f)),
024|     ( 0, (0x00,0x3f,0x7f)),
025| ]
026| 
027| ##------------------------------------------------------------------------------------------------##
028| Glider = [
029|     '!Name: Glider',
030|     '!',
031|     '.O.',
032|     '..O',
033|     'OOO',
034| ]
035| 
036| ##------------------------------------------------------------------------------------------------##
037| GliderGun = [
038|     '!Name: Gosper glider gun',
039|     '!Author: Bill Gosper',
040|     '!The first known gun and the first known finite pattern with unbounded growth.',
041|     '!www.conwaylife.com/wiki/index.php?title=Gosper_glider_gun',
042|     '........................O',
043|     '......................O.O',
044|     '............OO......OO............OO',
045|     '...........O...O....OO............OO',
046|     'OO........O.....O...OO',
047|     'OO........O...O.OO....O.O',
048|     '..........O.....O.......O',
049|     '...........O...O',
050|     '............OO',
051| ]
052| 
053| ##------------------------------------------------------------------------------------------------##
054| TitleLife = [
055|     '!Name: Title "Life"',
056|     '!Dims: 7x26',
057|     '!',
058|     'O......OOOOO..OOOOO..OOOOO',
059|     'O........O....O......O....',
060|     'O........O....O......O....',
061|     'O........O....OOO....OOO..',
062|     'O........O....O......O....',
063|     'O........O....O......O....',
064|     'OOOOO..OOOOO..O......OOOOO',
065| ]
066| 
067| ##------------------------------------------------------------------------------------------------##
068| TitleJohnConway = [
069|     '!Name: Title "John Conway"',
070|     '!Dims: 7x75',
071|     '!',
072|     'OOOOOO...OOO...O...O..O....O.....OOO....OOO...O....O..O.....O...OOO...O...O',
073|     '...O....O...O..O...O..OO...O....O...O..O...O..OO...O..O.....O..O...O..O...O',
074|     '...O....O...O..O...O..O.O..O....O......O...O..O.O..O..O.....O..O...O...O.O.',
075|     '...O....O...O..OOOOO..O..O.O....O......O...O..O..O.O..O.....O..OOOOO....O..',
076|     '...O....O...O..O...O..O...OO....O......O...O..O...OO..O..O..O..O...O....O..',
077|     'O..O....O...O..O...O..O....O....O...O..O...O..O....O...O.O.O...O...O....O..',
078|     'OOO......OOO...O...O..O....O.....OOO....OOO...O....O....OOO....O...O....O..',
079| ]
080| 
081| ##------------------------------------------------------------------------------------------------##
082| StartOptions = {
083|     'YT1/1':{'x':'1920', 'y':'1080', 'u':'1', 'v':'1'},     # 1920 x 1080
084|     'YT1/2':{'x':'1920', 'y':'1080', 'u':'2', 'v':'2'},     # 960 x 540
085|     'YT1/4':{'x':'1920', 'y':'1080', 'u':'4', 'v':'4'},     # 480 x 270
086|     'YT1/5':{'x':'1920', 'y':'1080', 'u':'5', 'v':'5'},     # 384 x 216
087|     'YT1/6':{'x':'1920', 'y':'1080', 'u':'6', 'v':'6'},     # 320 x 180
088|     'YT1/8':{'x':'1920', 'y':'1080', 'u':'8', 'v':'8'},     # 240 x 135
089|     'YT1/A':{'x':'1920', 'y':'1080','u':'10','v':'10'},     # 192 x 108
090|     'YT2/1':{'x':'1280', 'y': '720', 'u':'1', 'v':'1'},     # 1280 x 720
091|     'YT2/2':{'x':'1280', 'y': '720', 'u':'2', 'v':'2'},     # 640 x 360
092|     'YT2/4':{'x':'1280', 'y': '720', 'u':'4', 'v':'4'},     # 320 x 180
093|     'YT2/5':{'x':'1280', 'y': '720', 'u':'5', 'v':'5'},     # 256 x 144
094|     'YT3/1':{'x': '854', 'y': '480', 'u':'1', 'v':'1'},     # 854 x 480
095|     'YT3/2':{'x': '854', 'y': '480', 'u':'2', 'v':'2'},     # 427 x 240
096|     'HD/1': {'x':'1600', 'y': '900', 'u':'1', 'v':'1'},     # 1600 x 900
097|     'HD/2': {'x':'1600', 'y': '900', 'u':'2', 'v':'2'},     # 800 x 450
098|     'HD/4': {'x':'1600', 'y': '900', 'u':'4', 'v':'4'},     # 400 x 225
099|     'HD/5': {'x':'1600', 'y': '900', 'u':'5', 'v':'5'},     # 320 x 180
100|     '64/1': {'x': '640', 'y': '360', 'u':'1', 'v':'1'},     # 640 x 360
101|     '48/1': {'x': '480', 'y': '270', 'u':'1', 'v':'1'},     # 480 x 270
102|     '32/1': {'x': '320', 'y': '180', 'u':'1', 'v':'1'},     # 320 x 180
103|     '24/1': {'x': '240', 'y': '135', 'u':'1', 'v':'1'},     # 240 x 135
104|     '16/1': {'x': '160', 'y':  '90', 'u':'1', 'v':'1'},     # 160 x 90
105|     '64/2': {'x': '640', 'y': '360', 'u':'2', 'v':'2'},     # 320 x 180
106|     '48/2': {'x': '480', 'y': '270', 'u':'2', 'v':'2'},     # 240 x 135
107|     '32/2': {'x': '320', 'y': '180', 'u':'2', 'v':'2'},     # 160 x 90
108|     '24/2': {'x': '240', 'y': '135', 'u':'2', 'v':'2'},     # 120 x 67.5
109|     '16/2': {'x': '160', 'y':  '90', 'u':'2', 'v':'2'},     # 80 x 45
110| }
111| 
112| ##================================================================================================##
113| def get_life_pattern (patt):
114|     """Read text pattern and return data."""
115|     data = []
116|     for row in patt:
117|         if row.startswith('!'):
118|             continue
119|         cells = [1 if cell=='O' else 0 for cell in row]
120|         data.append(cells)
121|     maxlen = max([len(row) for row in data])
122|     for row in data:
123|         while len(row) < maxlen:
124|             row.append(0)
125|     return data
126| 
127| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
128| ##TODO save/resume
129| ##TODO run-time additions (to re-energize the pattern)
130| class ConwayLife (object):
131|     '''Conway Life Game.
131| 
131| Methods:
131|     reset           - initialize board
131|     go              - run the current configuration
131|     life_cycle      - execute one cycle
131|     insert_pattern  - add a pattern to the configuration
131|     save_frame      - create an image file
131|     save_plaintext  - save a plaintext file
131|     save_pov_data   - save data in POV format
131| 
131| '''

132|     class logger (object):
133|         def __init__ (self, log=None):
134|             self.log = log
135|         def sender (self, txt):
136|             if self.log:
137|                 self.log(txt)
138|         def info  (self, txt=''): self.sender(txt)
139|         def debug (self, txt=''): self.sender(txt)
140|         def trace (self, txt=''): self.sender(txt)
141|         def warm  (self, txt=''): self.sender(txt)
142|         def error (self, txt=''): self.sender(txt)
143| 
144|     class colorlist (object):
145|         def __init__ (self, list_of_colors):
146|             self._cs = []
147|             cc = 0
148|             for entry in list_of_colors:
149|                 self._cs.append((cc, entry[1]))
150|                 cc += entry[0]
151|         def __call__ (self, age):
152|             t = [c[1] for c in self._cs if c[0] <= age]
153|             return t[-1]
154|         def __len__ (self): return len(self._cs)
155|         def __getitem__ (self, ix): return self._cs[ix]
156| 
157|     def __init__ (self, dims, cell=(4,4), fname='life-%05d.png', fpath=r'C:\CJS\www\_dat', fmode='PNG', log=None):
158|         self.log = logger(log)
159|         self.log.info('Life::init(dims=%s, cell=%s)' % (dims,cell))
160|         self.dims = dims
161|         self.cell = cell
162|         self.fname = fname
163|         self.fpath = fpath
164|         self.fmode = fmode
165|         self.cols =  self.dims[0]//self.cell[0]
166|         self.rows =  self.dims[1]//self.cell[1]
167|         self.buf1 = [[0 for x in range(self.cols)] for y in range(self.rows)]
168|         self.buf2 = [[0 for x in range(self.cols)] for y in range(self.rows)]
169|         self.colors = ConwayLife.colorlist(LifeColors)
170|         self.cycle = 0
171|         self.wrap_edges = True
172|         self.save_zero_frame = False
173| 
174|     def go (self, cycles=20):
175|         '''Generate Life Cycles.'''
176|         self.log.info('Life::go(cycles=%d)' % cycles)
177|         if self.save_zero_frame:
178|             self.save_frame(0)
179|         # Cycle the life...
180|         for n in range(cycles):
181|             t0 = perf_counter()
182|             self.life_cycle()
183|             t1 = perf_counter()
184|             self.save_frame(1+n)
185|             t2 = perf_counter()
186|             #TODO: Save frame data option?
187|             print('Frame: %d/%d' % (n,cycles))
188|             self.log.debug('Life-Cycle: %.9f' % (t1-t0))
189|             self.log.debug('Save-Frame: %.9f' % (t2-t1))
190|             self.log.debug('Total-Time: %.9f' % (t2-t0))
191| 
192|     def reset (self, percentage=0.5):
193|         '''Reset and initialize the Life board.'''
194|         self.log.info('Life::reset(pct=%.3f)' % percentage)
195|         # Clear buffers to zero...
196|         self.buf1 = [[0 for c in range(self.cols)] for r in range(self.rows)]
197|         self.buf2 = [[0 for c in range(self.cols)] for r in range(self.rows)]
198|         self.cycle = 0
199|         # Initialize buffers with some life...
200|         for r in range(self.rows):
201|             for c in range(self.cols):
202|                 self.buf1[r][c] = (1 if random() < percentage else 0)
203| 
204|     def insert_pattern (self, row,col, pattern, revtb=False, revlr=False):
205|         '''Insert a pattern at a given row and column.'''
206|         patt = [list(reversed(row)) if revlr else list(row) for row in pattern]
207|         if revtb:
208|             patt = list(reversed(patt))
209|         for rx in range(len(patt)):
210|             for cx in range(len(patt[0])):
211|                 self.log.trace('buf1[%d][%d] = patt[%d][%d]'%(row+rx,col+cx,rx,cx))
212|                 self.buf1[row+rx][col+cx] = patt[rx][cx]
213| 
214|     def life_cycle (self):
215|         '''Execute one cycle of life.'''
216|         # For each row and column...
217|         for r in range(self.rows):
218|             for c in range(self.cols):
219|                 # Do the neighbor counts...
220|                 if self.wrap_edges:
221|                     self._count_neighbors_wrap(r,c)
222|                 else:
223|                     self._count_neighbors_no_wrap(r,c)
224|         # For each row and column...
225|         for r in range(self.rows):
226|             for c in range(self.cols):
227|                 # Apply the counts per the rules...
228|                 self._apply_rule(r,c)
229|         self.cycle += 1
230| 
231|     def _count_neighbors_no_wrap (self, row, col):
232|         '''Return a count number of living neighbors (no-wrap).'''
233|         self.log.trace('count: (%d, %d)' % (row,col))
234|         total = 0
235|         # Top row...
236|         if 0 < row:
237|             total += ((1 if 0 < self.buf1[row-1][col-1] else 0) if 0 < col else 0)
238|             total +=  (1 if 0 < self.buf1[row-1][col]   else 0)
239|             total += ((1 if 0 < self.buf1[row-1][col+1] else 0) if col < (self.cols-1) else 0)
240|         # Middle row...
241|         total += ((1 if 0 < self.buf1[row][col-1] else 0) if 0 < col else 0)
242|         total += ((1 if 0 < self.buf1[row][col+1] else 0) if col < (self.cols-1) else 0)
243|         # Bottom row...
244|         if row < (self.rows-1):
245|             total += ((1 if 0 < self.buf1[row+1][col-1] else 0) if 0 < col else 0)
246|             total +=  (1 if 0 < self.buf1[row+1][col]   else 0)
247|             total += ((1 if 0 < self.buf1[row+1][col+1] else 0) if col < (self.cols-1) else 0)
248|         # Save total in count(r,c)...
249|         self.buf2[row][col] = total
250|         self.log.trace('count=%d' % total)
251|         return total
252| 
253|     def _count_neighbors_wrap (self, row, col):
254|         '''Return a count number of living neighbors (wrap).'''
255|         self.log.trace('count: (%d, %d)' % (row,col))
256|         total = 0
257|         left = (self.cols-1) if col == 0 else (col-1)
258|         right = (col+1) if col < (self.cols-1) else 0
259|         top = (self.rows-1) if row == 0 else (row-1)
260|         bot = (row+1) if row < (self.rows-1) else 0
261|         # Top row...
262|         total += (1 if (0 < self.buf1[top][left] ) else 0)
263|         total += (1 if (0 < self.buf1[top][col]  ) else 0)
264|         total += (1 if (0 < self.buf1[top][right]) else 0)
265|         # Middle row...
266|         total += (1 if (0 < self.buf1[row][left] ) else 0)
267|         total += (1 if (0 < self.buf1[row][right]) else 0)
268|         # Bottom row...
269|         total += (1 if (0 < self.buf1[bot][left] ) else 0)
270|         total += (1 if (0 < self.buf1[bot][col]  ) else 0)
271|         total += (1 if (0 < self.buf1[bot][right]) else 0)
272|         # Save total in count(r,c)...
273|         self.buf2[row][col] = total
274|         self.log.trace('count=%d' % total)
275|         return total
276| 
277|     def _apply_rule (self, row, col):
278|         '''Apply rules to cell(r,c) based on count(r,c).'''
279|         m = self.buf1[row][col]
280|         n = self.buf2[row][col]
281|         self.buf1[row][col] = self._rule(m, n)
282| 
283|     def _rule (self, m, n):
284|         '''Return M (the life value) given N (the neighbor count).'''
285|         if 0 < m:
286|             # Cell is alive (needs 2 or 3 to survive)...
287|             return ((m+1) if (n in [2,3]) else 0)
288|         # Cell is dead (needs 3 to spawn)...
289|         return (1 if n == 3 else 0)
290| 
291|     def save_frame (self, frm_nbr):
292|         '''Generate an image from the buffer.'''
293|         filename = path.join(self.fpath, self.fname % frm_nbr)
294|         dims = (self.cols*self.cell[0], self.rows*self.cell[1])
295|         # Create image...
296|         im = Image.new('RGB', dims, (255,255,255))
297|         draw = ImageDraw.Draw(im)
298|         # For each row...
299|         for y in range(self.rows):
300|             # For each column...
301|             for x in range(self.cols):
302|                 # Get the cell value...
303|                 v = self.buf1[y][x]
304|                 # Calculate cell's ULC...
305|                 x0 = x * self.cell[0]
306|                 y0 = y * self.cell[1]
307|                 # Draw the cell...
308|                 for yy in range(self.cell[1]):
309|                     for xx in range(self.cell[0]):
310|                         draw.point((x0+xx,y0+yy), fill=self.colors(v))
311|         # Save the image...
312|         im.save(filename, self.fmode)
313|         self.log.debug('wrote: %s' % filename)
314|         return filename
315| 
316|     def save_plaintext (self, frm_nbr):
317|         '''Save buffer to plaintext data file.'''
318|         fn = path.join(self.fpath, self.fname % frm_nbr)
319|         fp = open(fn, mode='w', encoding='utf-8')
320|         try:
321|             out = ['!name: cjsPythonLife (buffer output)', '!']
322|             for y in range(self.rows):
323|                 row = [('O' if self.buf1[y][x] else '.') for x in range(self.cols)]
324|                 out.append(''.join(row))
325|             txt = '\n'.join(out)
326|             print(txt, file=fp)
327|             print(file=fp)
328|         except:
329|             raise
330|         finally:
331|             fp.close()
332| 
333|     def save_pov_data (self, frm_nbr):
334|         '''Save buffer to POV-readable data file. (comma-delimited numbers)'''
335|         fn = path.join(self.fpath, self.fname % frm_nbr)
336|         fp = open(fn, mode='w', encoding='utf-8')
337|         try:
338|             out = []
339|             for y in range(self.rows):
340|                 row = [('1' if self.buf1[y][x] else '0') for x in range(self.cols)]
341|                 out.append(','.join(row))
342|             txt = ',\n'.join(out)
343|             print(txt, file=fp)
344|             print(file=fp)
345|         except:
346|             raise
347|         finally:
348|             fp.close()
349| 
350|     def __str__ (self):
351|         t = (self.cycle, self.rows,self.cols, self.dims[0],self.dims[1], self.cell[0],self.cell[1], self.wrap_edges, self.save_zero_frame)
352|         s = "ConwayLife[%d]: %dx%d (%dx%d; %dx%d) W:%d ZF:%d"
353|         return s%t
354| 
355| 
356| ####################################################################################################
357| '''eof'''
358|