Last active
October 13, 2015 20:18
-
-
Save bennuttall/4250641 to your computer and use it in GitHub Desktop.
Conway's Game of Life
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
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