Time for action – simulating life
The following code is an implementation of Game of Life with some modifications, as follows:
Clicking once with the mouse draws a cross until we click again
Pressing the r key resets the grid to a random state
Pressing b creates blocks based on the mouse position
Pressing g creates gliders
The most important data structure in the code is a two-dimensional array holding the color values of the pixels on the game screen. This array is initialized with random values and then recalculated for each iteration of the game loop. More information about the involved functions can be found in the next section.
To evaluate the rules, we will use convolution, as follows.
def get_pixar(arr, weights): states = ndimage.convolve(arr, weights, mode='wrap') bools = (states == 13) | (states == 12 ) | (states == 3) return bools.astype(int)
We can draw a cross using basic indexing tricks that we learned in Chapter 2, Beginning with NumPy Fundamentals.
def draw_cross(pixar): ...