Guest User

Untitled

a guest
Nov 18th, 2018
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.07 KB | None | 0 0
  1. #Game of Life-implementaatio
  2. #tehnyt Jiggawatt Skrolli-lehteen
  3.  
  4. moore_nb = [
  5. (-1,-1), (0,-1), (1,-1),
  6. (-1, 0),         (1, 0),
  7. (-1, 1), (0, 1), (1, 1),
  8. ]
  9.  
  10. def surround(pos):
  11.     return [(pos[0]+nb[0], pos[1]+nb[1]) for nb in moore_nb]
  12.  
  13. class GameOfLife():
  14.     def __init__(self):        
  15.         self.board = {
  16.               (0,-1):1, (1,-1):1,
  17.     (-1,0):1, (0, 0):1,
  18.                   (0, 1):1,
  19.     }
  20.        
  21.         self.birth = [3]
  22.     self.survival = [2,3]
  23.    
  24.     self.turn = 0
  25.  
  26.     self.scr_w = 64
  27.     self.scr_h = 48
  28.  
  29.     def neighbours(self, area):
  30.         return len( [cell for cell in area if (cell in self.buffer)] )
  31.  
  32.     def user_input(self):
  33.         return raw_input("%s. vuoro - Enter jatkaaksesi, muutoin kirjoita 'quit' \n>" % self.turn)
  34.  
  35.     def store(self):
  36.     self.buffer = [cell for cell in self.board]
  37.  
  38.     def iterate(self):
  39.         dead_cells = {}     #oma bufferinsa mahd. uusille soluille - ei tarkisteta turhia alueita
  40.  
  41.         for alive in self.buffer:
  42.             live_nbs = 0
  43.             neighbours = surround(alive)
  44.  
  45.         for cell in neighbours:
  46.         if cell not in self.buffer:  #kuollut reunasolu
  47.             dead_cells[cell] = 1
  48.                 else:
  49.                     live_nbs += 1
  50.  
  51.             if live_nbs not in self.survival:
  52.                 del self.board[alive]          #kuolee
  53.  
  54.         for dead in dead_cells:
  55.             if self.neighbours(surround(dead)) in self.birth:
  56.                 self.board[dead] = 1            #syntyy
  57.  
  58.     def draw(self):
  59.         print '+' * (self.scr_w+2)
  60.        
  61.         for y in range(-self.scr_h/2, self.scr_h/2):
  62.             line = '+'
  63.            
  64.             for x in range(-self.scr_w/2, self.scr_w/2):
  65.                 line += '1' if (x,y) in self.board else ' '
  66.  
  67.             print line + '+'
  68.            
  69.         print '+' * (self.scr_w+2)
  70.  
  71.     def process(self):
  72.         self.turn += 1
  73.        
  74.         self.store()
  75.         self.iterate()
  76.         self.draw()
  77.  
  78.         return self.user_input() != 'quit'
  79.  
  80. ################ main ################
  81.  
  82. life = GameOfLife()
  83. while life.process():
  84.     pass
Add Comment
Please, Sign In to add comment