Created
September 16, 2012 09:48
-
-
Save basak/3731816 to your computer and use it in GitHub Desktop.
Elegant and minimalist implementation of Conway's Game of Life
This file contains hidden or 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
#!/usr/bin/python3 | |
# Conway's Game of Life | |
# Based on Jack Diederich's implementation | |
# http://pyvideo.org/video/880/stop-writing-classes | |
from itertools import chain, product | |
neighbour_deltas = set(list(product([-1, 0, 1], repeat=2))) - set([(0, 0)]) | |
def neighbour_points(point): | |
x, y = point | |
return ((x + dx, y + dy) for dx, dy in neighbour_deltas) | |
def advance(board): | |
new_board = set() | |
recalc = board | set(chain(*map(neighbour_points, board))) | |
for point in recalc: | |
count = sum(n_point in board for n_point in neighbour_points(point)) | |
if count == 3 or (count == 2 and point in board): | |
new_board.add(point) | |
return new_board | |
# Implementation ends here. Here is a use example: | |
def print_board(board, xrange=None, yrange=None): | |
if xrange is None: | |
xrange = min(p[0] for p in board), max(p[0] for p in board) + 1 | |
if yrange is None: | |
yrange = min(p[1] for p in board), max(p[1] for p in board) + 1 | |
for y in range(*yrange): | |
for x in range(*xrange): | |
print('*' if (x, y) in board else ' ', end='') | |
print() | |
print('--') | |
if __name__ == '__main__': | |
oscillator = set([(1, 1), (2, 1), (3, 1)]) | |
print_board(oscillator, (0, 4), (0, 4)) | |
for i in range(10): | |
oscillator = advance(oscillator) | |
print_board(oscillator, (0, 4), (0, 4)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment