Guest User

Untitled

a guest
Oct 7th, 2014
259
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.07 KB | None | 0 0
  1. from itertools import chain , product , repeat , izip , imap
  2. import pygame
  3.  
  4. def nextgen(generation):
  5.     newgen=set()
  6.     neighbors=lambda (x,y):((x+a,y+b) for a,b in product( [1,0,-1],[1,0,-1] ) if (a,b)!=(0,0) )
  7.     neighborhood=generation|set(chain(*map(neighbors,generation))) # union of all neighbors set and current generation set
  8.     for cell in neighborhood:
  9.         alive=len(set(neighbors(cell)) & generation) # number of alive neighbors of cell: length of the set
  10.         #got by intersection of current generation and neighbors of cell. ie: how many of the neighbors exist(are alive) in the current generation?
  11.         if (alive in [2,3] and cell in generation) or (alive ==3 and cell not in generation):
  12.             newgen.add(cell)
  13.     return newgen
  14.  
  15. def setup():
  16.     clock=pygame.time.Clock()
  17.     screen=pygame.display.set_mode(resolution)
  18.     return clock,screen
  19.  
  20. def getdim(generation):    
  21.     (maxx,minx),(maxy,miny)=map(lambda p:(max(p),min(p)), zip(*generation))
  22.     generation=set([(x-minx,y-miny) for x,y in generation])   # Normalize
  23.     width,height=maxx-minx+1,maxy-miny+1
  24.     return (width,height,generation)
  25.  
  26. def getrect((cell,dimension)):
  27.     w,h=dimension
  28.     rwidth=resolution[0]/(30) # dimensions of cells.30 X 30 grid
  29.     rheight=resolution[1]/(30)
  30.     position=(cell[0]*rwidth)+(resolution[0]/2)-((rwidth*w)/2),(cell[1]*rheight)+(resolution[1]/2)-((rheight*h)/2)
  31.     return pygame.Rect(position,(rwidth-2,rheight-2)) #the 2 is padding to distinguish between adjacent cells.
  32.  
  33. def paint(generation,screen):
  34.     w,h,generation=getdim(generation)
  35.     cells=imap(getrect,izip(generation,repeat( (w,h) ) ) )
  36.     for cell in cells:        
  37.         pygame.draw.rect(screen,red,cell,0)
  38.     pygame.display.flip()
  39.  
  40. red=255,0,0
  41. resolution=(600,600)
  42. clock,screen=setup()
  43. generation=set([(0,0),(1,0),(2,0)]) #blinker
  44. # generation=set([(0,0),(1,0),(2,0),(0,1),(1,1),(2,1),(0,2),(1,2),(2,2)]) # another pattern
  45. while pygame.event.poll().type!=pygame.QUIT:
  46.     clock.tick(500)
  47.     paint(generation,screen)    
  48.     generation=nextgen(generation)
  49.     pygame.time.delay(500)
  50.     screen.fill( (0,0,0) )
Advertisement
Add Comment
Please, Sign In to add comment