Guest User

Untitled

a guest
Nov 17th, 2018
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.17 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 = 24
  28.  
  29.     def store(self):
  30.     self.buffer = [cell for cell in self.board]
  31.  
  32.     def neighbours(self, area):
  33.         return len( [cell for cell in area if (cell in self.buffer)] )
  34.  
  35.     def iterate(self):
  36.         dead_cells = {}     #oma bufferinsa mahd. uusille soluille - ei tarkisteta turhia alueita
  37.  
  38.         for alive in self.buffer:
  39.             live_nbs = 0
  40.             neighbours = surround(alive)
  41.  
  42.         for cell in neighbours:
  43.         if cell not in self.buffer:  #kuollut reunasolu
  44.             dead_cells[cell] = 1
  45.                 else:
  46.                     live_nbs += 1
  47.  
  48.             if live_nbs not in self.survival:
  49.                 del self.board[alive]          #kuolee
  50.  
  51.         for dead in dead_cells:
  52.             if self.neighbours(surround(dead)) in self.birth:
  53.                 self.board[dead] = 1            #syntyy
  54.  
  55.     def draw(self):
  56.         print '+'*(self.scr_w+2)
  57.        
  58.         for y in range(-self.scr_h/2, self.scr_h/2):
  59.             line = '+'
  60.            
  61.             for x in range(-self.scr_w/2, self.scr_w/2):
  62.                 if (x,y) in self.board:
  63.                     line += '1'
  64.                 else:
  65.                     line += ' '
  66.                    
  67.             line += '+'
  68.             print line
  69.            
  70.         print '+'*(self.scr_w+2)
  71.  
  72.     def user_input(self):
  73.         return raw_input("%s. vuoro - Enter jatkaaksesi, muutoin kirjoita 'quit' \n>" % self.turn)
  74.  
  75.     def process(self):
  76.         self.turn += 1
  77.        
  78.         self.store()
  79.         self.iterate()
  80.         self.draw()
  81.  
  82.         return self.user_input() != 'quit'
  83.  
  84. ################ main ################
  85.  
  86. life = GameOfLife()
  87. while life.process():
  88.     pass
Add Comment
Please, Sign In to add comment