Created
November 2, 2016 15:52
-
-
Save PM2Ring/adcf1b1ce5fbbd839d224d5b29c93c54 to your computer and use it in GitHub Desktop.
Simple Game of Life engine using Numpy
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/env python3 | |
''' Game of Life in Numpy | |
Written by PM 2Ring 2016.11.03 | |
''' | |
import numpy as np | |
from time import sleep | |
offsets = ( | |
(0, 0), (0, 1), (0, 2), | |
(1, 0), (1, 2), | |
(2, 0), (2, 1), (2, 2), | |
) | |
newcell = np.vectorize(lambda g, k: np.uint8(k == 3 or g and k == 2)) | |
def evolve(grid): | |
numrows, numcols = grid.shape | |
padded = np.pad(grid, 1, 'constant', constant_values=0) | |
counts = empty_grid(numrows, numcols) | |
for r, c in offsets: | |
counts += padded[r:r+numrows, c:c+numcols] | |
return newcell(grid, counts) | |
def empty_grid(numrows, numcols): | |
return np.zeros((numrows, numcols), dtype='uint8') | |
def show(grid): | |
print('\x1bc', '\n'.join([' '.join(['-O'[v] for v in row]) | |
for row in grid]), sep='', end='\n\n') | |
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | |
glider = '''\ | |
.*. | |
..* | |
*** | |
''' | |
def mirrorX(pattern): | |
return '\n'.join([row[::-1] for row in pattern.splitlines()]) | |
def mirrorY(pattern): | |
return '\n'.join(reversed(pattern.splitlines())) | |
def add_pattern(grid, pattern, ox=0, oy=0): | |
numrows, numcols = grid.shape | |
for r, row in enumerate(pattern.splitlines(), oy): | |
if r >= numrows: | |
break | |
for c, v in enumerate(row, ox): | |
if c >= numcols: | |
break | |
if v not in ' .': | |
grid[r][c] = 1 | |
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | |
numrows, numcols = 40, 60 | |
grid = empty_grid(numrows, numcols) | |
gliderx = mirrorX(glider) | |
add_pattern(grid, glider, ox=1, oy=3) | |
add_pattern(grid, gliderx, ox=34, oy=2) | |
for _ in range(160): | |
show(grid) | |
grid = evolve(grid) | |
sleep(0.1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment