Created
October 1, 2013 16:33
-
-
Save robwiss/6781310 to your computer and use it in GitHub Desktop.
version of Nippashish's numpy gol engine that implements last_step
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
import numpy as np | |
from scipy import signal | |
import itertools | |
class Grid(object): | |
def __init__(self, rows, cols): | |
self._grid = np.zeros((rows, cols), dtype=np.float) | |
self._neighbourhood = np.array([ | |
[ 1, 1, 1 ], | |
[ 1, 0, 1 ], | |
[ 1, 1, 1 ], | |
], dtype=np.float) | |
self._last_step = None | |
def tick(self): | |
neighbour_counts = np.round(signal.fftconvolve( | |
self._grid, self._neighbourhood, | |
mode='same')) | |
birth = neighbour_counts == 3 | |
survive = np.logical_and(self._grid, neighbour_counts == 2) | |
newgrid = np.logical_or(birth, survive).astype(np.float) | |
changed = np.logical_xor(self._grid, newgrid) | |
changed_indices = np.nonzero(changed) | |
changed_values = newgrid[changed_indices].astype(np.bool) | |
self._grid = newgrid | |
self._last_step = itertools.izip(np.transpose(changed_indices), changed_values) | |
@property | |
def rows(self): | |
return self._grid.shape[0] | |
@property | |
def cols(self): | |
return self._grid.shape[1] | |
@property | |
def last_step(self): | |
return self._last_step | |
def is_alive(self, row, col): | |
return self._grid[row,col] != 0 | |
def set_alive(self, row, col): | |
self._grid[row,col] = 1 | |
def set_dead(self, row, col): | |
self._grid[row,col] = 0 | |
def iterindexes(self): | |
for row in xrange(self.rows): | |
for col in xrange(self.cols): | |
yield (row, col) | |
raise StopIteration |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment