#!/usr/bin/env python
# coding: utf-8

# In[1]:


get_ipython().run_line_magic('matplotlib', 'inline')
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import animation
matplotlib.rcParams['animation.html'] = 'html5'


# In[2]:


from functools import reduce
from random import randint


# In[3]:


NUM = 64
LEVEL = 8

def randomBoard():
    return [[randint(0, 1) for col in range(NUM)] for row in range(NUM)]

def nextBoard(board):
    torus = lambda i: NUM - 1 if i == -1 else 0 if i == NUM else i
    count = lambda i, j: len([(k, l) for k in [i - 1, i, i + 1] for l in [j - 1, j, j + 1] 
                              if not (k == i and l == j) and board[torus(k)][torus(l)] != 0])
    liveOrDead = lambda n: n == 2 or n == 3
    birth = lambda n: n == 3
    cell = lambda c, n: 1 if c == 0 and birth(n) else min(c + 1, LEVEL) if c != 0 and liveOrDead(n) else 0
    return [[cell(board[i][j], count(i, j)) for j in range(NUM)] for i in range(NUM)]


# In[4]:


board = randomBoard()
plt.matshow(board, vmin=0, vmax=NUM)


# In[5]:


board = nextBoard(board)
plt.matshow(board, vmin=0, vmax=LEVEL)


# In[6]:


FRAMES = 100

boards = [randomBoard()]
for i in range(1, FRAMES):
    boards.append(nextBoard(boards[i-1]))

fig = plt.figure(figsize=(8,8))

def getArtist(board):
    ax = plt.axes(xlim=(0, NUM-1), ylim=(0, NUM-1)) # specify matrix size
    return ax.matshow(board, vmin=0, vmax=LEVEL)

artists = [[getArtist(b)] for b in boards] # [python - Matplotlib Animation - Stack Overflow](http://stackoverflow.com/questions/18019226/matplotlib-animation)
animation.ArtistAnimation(fig, artists, interval=200, repeat=False)


# In[ ]: