Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #Game of Life-implementaatio
- #tehnyt Jiggawatt Skrolli-lehteen
- moore_nb = [
- (-1,-1), (0,-1), (1,-1),
- (-1, 0), (1, 0),
- (-1, 1), (0, 1), (1, 1),
- ]
- def surround(pos):
- return [(pos[0]+nb[0], pos[1]+nb[1]) for nb in moore_nb]
- class GameOfLife():
- def __init__(self):
- self.board = {
- (0,-1):1, (1,-1):1,
- (-1,0):1, (0, 0):1,
- (0, 1):1,
- }
- self.birth = [3]
- self.survival = [2,3]
- self.turn = 0
- self.scr_w = 64
- self.scr_h = 48
- def neighbours(self, area):
- return len( [cell for cell in area if (cell in self.buffer)] )
- def user_input(self):
- return raw_input("%s. vuoro - Enter jatkaaksesi, muutoin kirjoita 'quit' \n>" % self.turn)
- def store(self):
- self.buffer = [cell for cell in self.board]
- def iterate(self):
- dead_cells = {} #oma bufferinsa mahd. uusille soluille - ei tarkisteta turhia alueita
- for alive in self.buffer:
- live_nbs = 0
- neighbours = surround(alive)
- for cell in neighbours:
- if cell not in self.buffer: #kuollut reunasolu
- dead_cells[cell] = 1
- else:
- live_nbs += 1
- if live_nbs not in self.survival:
- del self.board[alive] #kuolee
- for dead in dead_cells:
- if self.neighbours(surround(dead)) in self.birth:
- self.board[dead] = 1 #syntyy
- def draw(self):
- print '+' * (self.scr_w+2)
- for y in range(-self.scr_h/2, self.scr_h/2):
- line = '+'
- for x in range(-self.scr_w/2, self.scr_w/2):
- line += '1' if (x,y) in self.board else ' '
- print line + '+'
- print '+' * (self.scr_w+2)
- def process(self):
- self.turn += 1
- self.store()
- self.iterate()
- self.draw()
- return self.user_input() != 'quit'
- ################ main ################
- life = GameOfLife()
- while life.process():
- pass
Add Comment
Please, Sign In to add comment