In [1]:
import matplotlib.image as image
import numpy as np
from PIL import Image
import copy
def pintar(img,x0,x1,y0,y1,color):
for x in range(int(x0),int(x1)):
for y in range(int(y0),int(y1)):
img[x][y] = np.array(color)
def getVecinos(jv,i,j):
ans = 0
if 0 <= i-1 and 0 <= j-1 and jv[i-1][j-1]:
ans += 1
if 0 <= i-1 and jv[i-1][j]:
ans += 1
if 0 <= i-1 and j+1 < jv.shape[1] and jv[i-1][j+1]:
ans += 1
if 0 <= j-1 and jv[i][j-1]:
ans += 1
if j+1 < jv.shape[1] and jv[i][j+1]:
ans += 1
if i+1 < jv.shape[0] and 0 <= j-1 and jv[i+1][j-1]:
ans += 1
if i+1 < jv.shape[0] and jv[i+1][j]:
ans += 1
if i+1 < jv.shape[0] and j+1 < jv.shape[1] and jv[i+1][j+1]:
ans += 1
return ans
def juegoDeLaVida(n,longitud,tiempo):
img = np.ones((n*longitud,n*longitud,3))
jv = np.zeros((n,n))
imagenes = []
imagenes.append(Image.fromarray(np.uint8(np.ones((n*longitud,n*longitud,3))*255)))
np.random.seed(1234567)
for i in range(n):
for j in range(n):
if np.random.randint(100) < 23:
jv[i][j] = 1
for _ in range(tiempo):
jvt = copy.deepcopy(jv)
for i in range(n):
for j in range(n):
color = [0,0,0]
v = getVecinos(jvt,i,j)
if jvt[i][j] == 0: #muerta
if v == 3:
jv[i][j] = 1
else:
if v == 2 or v == 3:
jv[i][j] = 1
else:
jv[i][j] = 0
if jv[i][j]:
color = [1,1,1]
pintar(img,(i)*longitud,(i+1)*longitud,(j)*longitud,(j+1)*longitud,color)
imagenes.append(Image.fromarray(np.uint8(img*255)))
imagenes[0].save('gif.gif',
save_all=True,
append_images=imagenes[1:],
optimize=False,
duration=500,
loop=0)
return 1
juegoDeLaVida(12,10,10)
Out[1]:
Reglas del juego:
- Una célula muerta con exactamente 3 células vecinas vivas "nace".
- Una célula viva con 2 o 3 células vecinas vivas sigue viva, en otro caso muere.
No hay comentarios.:
Publicar un comentario