Skip to content

Instantly share code, notes, and snippets.

@slagyr
Created February 27, 2019 02:17
Show Gist options
  • Save slagyr/5839fc5a26cb33100ddc2b6b587fe5f5 to your computer and use it in GitHub Desktop.
Save slagyr/5839fc5a26cb33100ddc2b6b587fe5f5 to your computer and use it in GitHub Desktop.
Game of Life in Python
from funcy import mapcat
class Pyfe:
def __init__(self):
self._living_cells = set()
@property
def living_cells(self):
return self._living_cells
@living_cells.setter
def living_cells(self, cells):
self._living_cells = cells
def toggle(self, x, y):
cell = (x, y)
if cell in self._living_cells:
self._living_cells.discard(cell)
else:
self._living_cells.add(cell)
def tick(self):
neighbors_fn = lambda x: self.neighbors_of(x)
all_neighbors = mapcat(neighbors_fn, self.living_cells)
neighbor_counts = self.frequencies(all_neighbors)
alive_fn = lambda x: self.is_alive(x, neighbor_counts[x])
next_gen = filter(alive_fn, neighbor_counts.keys())
self._living_cells = set(next_gen)
def neighbors_of(self, cell):
x, y = cell
neighbors = [(x + dx, y + dy) for dx in [-1, 0, 1] for dy in [-1, 0, 1]]
neighbors = set(neighbors)
neighbors.discard(cell)
return neighbors
def frequencies(self, cells):
result = {}
for cell in cells:
if cell in result:
freq = result[cell]
result[cell] = freq + 1
else:
result[cell] = 1
return result
def is_alive(self, cell, neighbors):
if neighbors == 2 and cell in self._living_cells:
return True
elif neighbors == 3:
return True
else:
return False
# -----------------------------
# Snippet from test file
class PyfeTest(unittest.TestCase):
def test_blinker(self):
self._life.living_cells = {(0, 0), (1, 0), (-1, 0)}
self._life.tick()
self.assertEqual({(0, 0), (0, -1), (0, 1)}, self._life.living_cells)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment