-
-
Save jgomezdans/3370483 to your computer and use it in GitHub Desktop.
Array-oriented version of the 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
from numpy.random import rand | |
from numpy import r_, ix_, uint8, roll | |
import matplotlib.pyplot as plt | |
import time | |
size = 200 | |
GRID = (rand(size,size) > 0.75).astype(uint8) | |
# Rotate indices because the world is round | |
indx = r_[0:size] | |
up = roll(indx, -1) | |
down = roll(indx, 1) | |
fig = plt.figure() | |
ax = fig.add_subplot(111) | |
img = ax.imshow(GRID,interpolation='nearest',cmap='gray') | |
def update_image(idleevent): | |
if update_image.i==2000: | |
return False | |
global GRID | |
neighbors = GRID[up,:] + GRID[down,:] + GRID[:,up] + GRID[:,down] + \ | |
GRID[ix_(up,up)] + GRID[ix_(up,down)] + GRID[ix_(down,up)] + \ | |
GRID[ix_(down,down)] | |
GRID = (neighbors == 3) | (GRID & (neighbors==2)) | |
img.set_data(GRID) | |
fig.canvas.draw_idle() | |
time.sleep(0.02) | |
update_image.i += 1 | |
update_image.i = 0 | |
import wx | |
wx.EVT_IDLE(wx.GetApp(), update_image) | |
plt.show() |
And clearly, there's wrapping round of the edges, that's what the np.roll
bit does
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Quite a cool example, but let's see how the neighbourhood calculation works....
GRID[up, :]
is the row below the current rowGRID[down,:]
is the row above the current rowGRID[:, up]
is the column to the right of the current columnGRID[:, down]
is the column to the left of the current columnGRID[ix_(up,up)]
is the bottom right rowGRID[ix_(up, down)]
is the bottom left rowGRID[ix_(down,up)]
is the above right rowGRID[ix_(up,up)]
is the above left row