Conway


wxPythonics back to page of py snippets

""" Mr Conway_s   Game Of Life   simulation in python 2 and 3  in 36 lines of code, essentially 30 lines """
import time , itertools
width = 30 ;  height = 30 # size of life habitat 30x30  - could be a simulated meteorite, bolide, boreal forest 
vmap  = [['D' for w  in range(width)] for h in range(height)]           # D = Dead at first

def neighbours(point):
 x,y = point
 yield x + 1 , y     ;  yield x - 1 , y ;  yield x     , y + 1 ;  yield x     , y - 1 ;   yield x + 1 , y + 1  ;  yield x + 1 , y - 1 ;  yield x - 1 , y + 1 ;  yield x - 1 , y - 1
 
def ageing(habitat):
 newstate = set()
 recalc   = habitat | set(itertools.chain(*map(neighbours,  habitat)))   # The "RNA-world hypothesis" is for real. This is proof.
 for point in recalc:
  count = sum((neigh in habitat) for neigh in  neighbours(  point))
  if count == 3 or (count == 2 and point in               habitat):      # standard rule definition: A life cell having less than 2 alive neighbours will die
   newstate.add(point)
 return newstate

glider   = set([ (40,40) , (41,40) , (42,40) , (40,41) , (41,42)   ])    # patterns of life: gliders, boats, guns, imps, toads, pulsars and so on
previous = set([ ( 0, 0) , ( 1, 0) , ( 2, 0) , ( 0, 1) , ( 1, 2)   ])    # offset on screen / place during last step in life

for lifetime in range(300):                                              # number of simulated lifetime steps (e.g. 300 / 0.1 sleep = 30 seconds) before death occurs
  try:
   time.sleep( 0.1 )                                                     # slow it down
   previous  = glider          ;  glider = ageing(glider)
   for  tup       in  glider   :  
     el=tup ;     xx=el[0] % width    ;     yy =el[1] % height ; vmap[xx][yy]='L'   # Live cell has emerged
   for  tup       in  previous :  
     el=tup ;     xx=el[0] % width    ;     yy =el[1] % height  
     if tup not   in  glider   :   vmap[xx][yy]='D'                                 # Dead cell             
   # put more life patterns in this lifespan loop and let them evolutionize!
   vtxt = [''.join('*' if cell=='L' else ' ' for cell in row) for row in vmap]        
   print('\033[H\033[J')                                                            # clear screen
   print('\n'.join(reversed(vtxt))) 
  except: pass
print("Simulated lifetime of the glider is over. May there live soon a new glider in the life habitat of your screen.") 

Last modified : 2018/01/02 00:56:39 UTC