Last active
January 12, 2016 22:05
-
-
Save daramcq/d86ff530415cef18472a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/python | |
class Game(object): | |
def __init__(self, dimensions, cell_set): | |
self.dimensions = dimensions | |
self.cell_set = cell_set | |
def adjacent(self, a, b): | |
return abs(a[0] - b[0]) < 2 and abs(a[1] - b[1]) < 2 | |
def getLiveNeighbours(self, pos): | |
alive = self.cell_set.difference(set([pos])) | |
live_neighbours = [t for t in alive if self.adjacent(t, pos)] | |
return len(live_neighbours) | |
def checkSurvives(self, live_neighbours): | |
return live_neighbours > 1 and live_neighbours < 4 | |
def checkIsBorn(self, live_neighbours): | |
return live_neighbours == 3 | |
def positionLives(self, pos): | |
neighbours = self.getLiveNeighbours(pos) | |
alive_now = pos in self.cell_set | |
return (self.checkSurvives(neighbours) if alive_now | |
else self.checkIsBorn(neighbours)) | |
def stepGame(self): | |
grid = [pos for pos in getGrid(*self.dimensions)] | |
new_cell_set = set([pos for pos in grid | |
if self.positionLives(pos)]) | |
return Game(dimensions, new_cell_set) | |
def getGrid(w,h): | |
for x in range(w): | |
for y in range(h): | |
yield (x,y) | |
def getChar(pos, game): | |
alive = pos in game.cell_set | |
end_cell = pos[1] is game.dimensions[1] - 1 | |
char = ( " X" if alive else " _") | |
char = char + "\n" if end_cell else char | |
return char | |
def drawGame(game, dimensions): | |
chars = [getChar(pos, game) for pos in getGrid(*dimensions)] | |
print "".join(chars) | |
if __name__ == '__main__': | |
steps = 5 | |
dimensions = (5,5) | |
cell_set = set([(1,2),(3,3),(2,1),(2,2),(4,5)]) | |
game = Game(dimensions, cell_set) | |
for i in range(steps): | |
game = game.stepGame() | |
drawGame(game, dimensions) | |
print "" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment