Skip to content

Instantly share code, notes, and snippets.

@bennuttall
Last active October 13, 2015 20:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bennuttall/4250641 to your computer and use it in GitHub Desktop.
Save bennuttall/4250641 to your computer and use it in GitHub Desktop.
Conway's Game of Life
def evolve_cell(alive, neighbours):
if alive:
return neighbours in [2, 3]
return neighbours == 3
def count_neighbours(alive_cells, position):
r, c = position
neighbours = [(r - 1, c - 1), (r - 1, c + 0), (r - 1, c + 1),
(r + 0, c - 1), (r + 0, c + 1),
(r + 1, c - 1), (r + 1, c + 0), (r + 1, c + 1)]
return sum(cell in alive_cells for cell in neighbours)
def evolve(alive_cells, size):
new_alive_cells = set()
rows, cols = size
for r in range(rows):
for c in range(cols):
cell = (r, c)
alive = cell in alive_cells
neighbours = count_neighbours(alive_cells, cell)
if evolve_cell(alive, neighbours):
new_alive_cells.add(cell)
return new_alive_cells
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment