Skip to content

Instantly share code, notes, and snippets.

@kumikoda
Created June 9, 2017 00:19
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 kumikoda/19ae4e68f6b4a7ffefb30b75165ce5f4 to your computer and use it in GitHub Desktop.
Save kumikoda/19ae4e68f6b4a7ffefb30b75165ce5f4 to your computer and use it in GitHub Desktop.
game of life in python
from sets import Set
class Game:
def __init__(self, state):
self.state = state
def next(self):
new_state = Set()
for cell in state:
# compute next state for this cell
if 2 <= self.count_neighbours(cell) <= 3:
new_state.add(cell)
# check if dead neighbours alive next?
x, y = cell
for i in range(x-1, x+2):
for j in range(y-1, y+2):
if (i != x or j != y) and (i, j) in state:
pass
else:
if self.count_neighbours((i, j)) == 3:
new_state.add((i, j))
self.state = new_state
def count_neighbours(self, cell):
live_neighbour_count = 0
x, y = cell
for i in range(x-1, x+2):
for j in range(y-1, y+2):
if (i != x or j != y) and (i, j) in state:
live_neighbour_count = live_neighbour_count + 1
return live_neighbour_count
state = Set([(0, 0), (0, 1), (0, 2)])
g = Game(state)
g.next()
print g.state
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment