-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGameofLife.py
112 lines (89 loc) · 2.33 KB
/
GameofLife.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# coding: utf-8
# In[1]:
import numpy as np
import matplotlib.pyplot as plt
#%matplotlib inline
import time
from IPython.display import clear_output, Image, display
import imageio
import scipy.misc
#import skimage.transform
import progressbar
from numba import jit
# In[2]:
def generate_map(sidelength):
map = np.random.randint(2, size=(sidelength, sidelength))
return map
def plot_map(map,fps):
fig = plt.figure(figsize=(12,12))
plt.imshow(map, cmap='binary')
plt.show()
plt.pause(1/fps)
clear_output(wait=True)
@jit
def count_nn(map, position):
nn = 0
x = position[0]
y = position [1]
if(map[x+1,y+1] == 1):
nn = nn+1
if(map[x-1,y+1] == 1):
nn = nn+1
if(map[x+1,y-1] == 1):
nn = nn+1
if(map[x-1,y-1] == 1):
nn = nn+1
if(map[x,y+1] == 1):
nn = nn+1
if(map[x,y-1] == 1):
nn = nn+1
if(map[x+1,y] == 1):
nn = nn+1
if(map[x-1,y] == 1):
nn = nn+1
else:
pass
return nn
@jit
def forward(map):
rows = np.shape(map)[0]
cols = np.shape(map)[1]
newmap = np.zeros((rows,cols))
for x in range(1,cols-1):
for y in range(1,rows-1):
nn = count_nn(map,(x,y))
if(map[x,y]==0 and nn==3):
newmap[x,y]=1
if(map[x,y]==1 and nn<2):
newmap[x,y]=0
if(map[x,y]==1 and (nn==2 or nn==3)):
newmap[x,y]=1
if(map[x,y]==1 and nn>3):
newmap[x,y]=0
return newmap
@jit
def simplegameoflife(sidelength, iterations):
map=generate_map(sidelength)
for i in range(iterations):
plot_map(map,100)
map=forward(map)
@jit
def scale_array(x, new_size):
min_el = np.min(x)
max_el = np.max(x)
y = scipy.misc.imresize(x, new_size, mode='L', interp='nearest')
y = y / 255 * (max_el - min_el) + min_el
return y
@jit
def gameoflife_2_gif(sidelength, iterations):
images = []
map = generate_map(sidelength)
bar = progressbar.ProgressBar(max_value=iterations)
for i in range(iterations):
scaledmap = scale_array(map,(1000,1000))
images.append(scaledmap)
map = forward(map)
bar.update(i)
imageio.mimsave('population.gif', images)
# In[6]:
gameoflife_2_gif(110,1000)