Skip to content

Instantly share code, notes, and snippets.

@thara
Last active March 31, 2020 01:28
Show Gist options
  • Save thara/ded6dd880ba95580088ef8875abb05e5 to your computer and use it in GitHub Desktop.
Save thara/ded6dd880ba95580088ef8875abb05e5 to your computer and use it in GitHub Desktop.
Conway's Game of Life written in Python, except classes : via 'Stop Writing Classes' https://youtu.be/o9pEzgHorH0?t=1178
from itertools import chain
import time
def neighbors(point):
x, y = point
return ((x + i, y + j) for i in [-1, 0, 1] for j in [-1, 0, 1] if (i, j) != (0, 0))
def is_living(point, live_cells):
count = sum(1 for n in neighbors(point) if n in live_cells)
return count == 3 or (count == 2 and point in live_cells)
def advance(live_cells):
cells = live_cells | set(chain.from_iterable(neighbors(p) for p in live_cells))
return set(x for x in cells if is_living(x, live_cells))
def print_board(live_cells):
for y in range(15):
for x in range(30):
mark = "*" if (x, y) in live_cells else "-"
print(mark, end='')
print("")
live_cells = {(0, 1), (1, 2), (2, 0), (2, 1), (2, 2)}
live_cells = live_cells | set((x + 5, y + 3) for (x, y) in live_cells)
print_board(live_cells)
while True:
time.sleep(0.3)
print("\033[15A\r", end='')
live_cells = advance(live_cells)
print_board(live_cells)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment