Last active
June 19, 2016 03:55
-
-
Save bign8/5b381c30063432a6994451e7305bc827 to your computer and use it in GitHub Desktop.
Conway's Game of life from 2012 Pycon
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
""" | |
Based on 2012 Pycon Talk: "Stop Writing Classes" by Jack Diederich | |
- https://us.pycon.org/2012/schedule/presentation/352/ | |
Noted rules from Wikipedia: https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life | |
1. Any live cell with fewer than two live neighbours dies, as if caused by under-population. | |
2. Any live cell with two or three live neighbours lives on to the next generation. | |
3. Any live cell with more than three live neighbours dies, as if by over-population. | |
4. Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction. | |
""" | |
import itertools | |
def neighbors(point): | |
x, y = point | |
yield x + 1, y | |
yield x - 1, y | |
yield x, y + 1 | |
yield x, y - 1 | |
yield x + 1, y + 1 | |
yield x + 1, y - 1 | |
yield x - 1, y + 1 | |
yield x - 1, y - 1 | |
def advance(board): | |
newstate = set() | |
recalc = board | set(itertools.chain(*map(neighbors, board))) | |
for point in recalc: | |
count = sum((neigh in board) for neigh in neighbors(point)) | |
if count == 3 or (count == 2 and point in board): | |
newstate.add(point) | |
display(newstate) | |
return newstate | |
def display(board): | |
top_x = max(board, key=lambda p: p[0])[0] | |
top_y = max(board, key=lambda p: p[1])[1] | |
bot_x = min(board, key=lambda p: p[0])[0] | |
bot_y = min(board, key=lambda p: p[1])[1] | |
dx = top_x - bot_x + 1 | |
dy = top_y - bot_y + 1 | |
grid = [[' ' for _ in range(dy)] for _ in range(dx)] | |
for cell in board: | |
grid[top_x-cell[0]][top_y-cell[1]] = 'x' | |
divider = '|--' + ('-+--' * (dy - 1)) + '-|\n' | |
for row in grid: | |
print divider + '| ' + ' | '.join(row) + ' |' | |
print divider | |
glider = set([(0, 0), (1, 0), (2, 0), (0, 1), (1, 2)]) | |
display(glider) | |
for i in range(1000): | |
glider = advance(glider) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment