# Game of life using NumPy

I'm trying to improve my Game of life program for school in Python, to be able to run it quicker. So if you have some ideas, I will be glad to hear them.

My current code:

def neighbourhood(m, i, j):
num = 0
n_board = len(m)
for k in range(i-1,i+2):
for l in range(j-1,j+2):
if k < 0 or l < 0 or k >= n_board or l >= n_board:
num = num + 0
else:
num = num + m[k][l]
return num

def update(m):
s = np.copy(m)
n_board = len(m)
for i in range(0, n_board):
for j in range(0, n_board):
if s[i][j] == 1:
num = neighbourhood(s, i, j) - 1
if num <= 1 or num > 3:
m[i][j] = 0
else:
m[i][j] = 1
else:
num = neighbourhood(s, i, j)
if num == 3:
m[i][j] = 1
else:
m[i][j] = 0

def square(x, y):
turtle.penup()
turtle.setposition(x,y)
turtle.pendown()
turtle.begin_fill()
for i in range(4):
turtle.forward(0.9)
turtle.left(90)
turtle.end_fill()

def draw(m):
turtle.clear()
n_board = len(m)
for i in range(n_board):
for j in range(n_board):
if m[i][j] == 1:
square(j, (n_board - i - 1))
turtle.update()

def main(n_board):
turtle.reset()
turtle.setworldcoordinates(0, 0, n_board, n_board)
turtle.hideturtle()
turtle.speed('fastest')
turtle.tracer(0, 0)
turtle.color('black')
turtle.bgcolor('white')
board=np.zeros((n_board, n_board), int)
for i in range(n_board):
for j in range(n_board):
if random() < 0.5:
board[i][j] = 1
draw(board)
for k in range(100):
update(board)
draw(board)


So as you can see for the moment i'm only doing 100 repetition and the starting board is randomly created.

• Welcome to code review. It might be better if your title was about what the code does rather than about the results you are trying to achieve. For a little more help on asking good questions please see the code review guidelines at codereview.stackexchange.com/help/how-to-ask and codereview.stackexchange.com/help/dont-ask. – pacmaninbw Jul 31 '19 at 12:16
• You mention that you are using turtles to display the board. Nothing in your code shows this. You can only ask about code that you show in your question. Since we are on Code Review, complete code is often preferable to shortened code. – AlexV Jul 31 '19 at 12:46