I'm totally new to python and coding in general and I tried for my first project to recreate Conway's game of life. After days of trial and error, I came up with this code:
import numpy as np
import copy
import png
import PIL as PIL
def a(a) :
if a == "gen" :
size=int(input("size ? "))
ratio=float(input("ratio ? "))
name=input("file name: ")
matrix=np.random.choice(2,(size,size),p=[1-ratio,ratio])
i = png.from_array(matrix, mode='L;1')
i.save(str(name)+'.JPEG')
if a == "start" :
name=input("file name: ")
time=input('number of rounds: ')
matrix=np.asarray(PIL.Image.open(str(name)+'.jpeg')).astype(int)
matrix2=copy.deepcopy(matrix)
taille1,taille2=matrix.shape
counter=0
while counter<int(time):
for x in range(0,taille1-1):
for y in range(0,taille2-1):
if matrix[x,y]==0 and matrix[x+1,y]+matrix[x,y+1]+matrix[x+1,y+1]+matrix[x-1,y]+matrix[x,y-1]+matrix[x-1,y-1]+matrix[x-1,y+1]+matrix[x+1,y-1]==3:
matrix2[x,y]=1
if matrix[x,y]==1 and matrix[x+1,y]+matrix[x,y+1]+matrix[x+1,y+1]+matrix[x-1,y]+matrix[x,y-1]+matrix[x-1,y-1]+matrix[x-1,y+1]+matrix[x+1,y-1]<2:
matrix2[x,y]=0
if matrix[x,y]==1 and matrix[x+1,y]+matrix[x,y+1]+matrix[x+1,y+1]+matrix[x-1,y]+matrix[x,y-1]+matrix[x-1,y-1]+matrix[x-1,y+1]+matrix[x+1,y-1]>3:
matrix2[x,y]=0
i = png.from_array(matrix2, mode='L;1')
i.save(str(name)+'_output_'+str(counter+1)+'.JPEG')
matrix=copy.deepcopy(matrix2)
counter+=1
task=input("command : ")
a(task)
It works really fine but I'm afraid it is quite unefficient, so I'd like to hear advice on how to make it faster (especially the triple loop)