Skip to content

Instantly share code, notes, and snippets.

@AntonKueltz
Created November 13, 2018 23:42
Show Gist options
  • Save AntonKueltz/c163af99d1b190beeaf1e002f8a01ad6 to your computer and use it in GitHub Desktop.
Save AntonKueltz/c163af99d1b190beeaf1e002f8a01ad6 to your computer and use it in GitHub Desktop.
from time import sleep
class Cell:
ALIVE = True
DEAD = False
def __init__(self, status):
self.status = status
def __str__(self):
if self.status == self.ALIVE:
return 'O'
else:
return '.'
def next_status(self, neighbors):
count = sum([1 for n in neighbors if n.status == self.ALIVE])
if self.status == self.ALIVE:
return self.ALIVE if (count in [2, 3]) else self.DEAD
else:
return self.ALIVE if (count == 3) else self.DEAD
class Grid:
def __init__(self, seed):
self.height = len(seed)
self.width = len(seed[0])
self.state = []
for row in seed:
cells = [Cell(state) for state in row]
self.state.append(cells)
def display(self):
for row in self.state:
print(' '.join([str(cell) for cell in row]))
def _neighbors(self, i, j):
cells = []
for x in range(max(0, i-1), min(self.height, i+2)):
for y in range(max(0, j-1), min(self.width, j+2)):
if x == i and y == j:
continue
cells.append(self.state[x][y])
return cells
def update(self):
new_state = []
for (i, row) in enumerate(self.state):
new_row = []
for (j, cell) in enumerate(row):
neighbors = self._neighbors(i, j)
next_cell = Cell(cell.next_status(neighbors))
new_row.append(next_cell)
new_state.append(new_row)
self.state = new_state
if __name__ == '__main__':
seed = [
[False, False, False, False, False, False],
[False, False, False, False, False, False],
[False, True, True, False, False, False],
[False, True, True, False, False, False],
[False, False, False, True, True, False],
[False, False, False, True, True, False],
[False, False, False, False, False, False]
]
grid = Grid(seed)
while True:
grid.display()
sleep(1)
grid.update()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment