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.setheading(0)
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.