︠ac12bda9-3eac-4b4d-90aa-0f96bac05be7︠ import numpy def one_tick(B): # Count neighbours N = (B[0:-2,0:-2] + B[0:-2,1:-1] + B[0:-2,2:] + B[1:-1,0:-2] + B[1:-1,2:] + B[2: ,0:-2] + B[2: ,1:-1] + B[2: ,2:]) # Apply rules birth = (N==3) & (B[1:-1,1:-1]==0) survive = ((N==2) | (N==3)) & (B[1:-1,1:-1]==1) B[...] = 0 B[1:-1,1:-1][birth | survive] = 1 return B ︠3df07e4a-1073-49db-b31d-1c01118af36f︠ # Create a simple glider Z = numpy.array([[0,0,0,0,0,0], [0,0,0,1,0,0], [0,1,0,1,0,0], [0,0,1,1,0,0], [0,0,0,0,0,0], [0,0,0,0,0,0]]) Z ︠c8139636-4781-458b-aa21-f54a4c6704d5︠ matrix_plot(Z, cmap=["white", "red"]) ︠f4342c11-3f4b-4faf-9958-d7048fe1a12c︠ Z = one_tick(Z) matrix_plot(Z, cmap=["white", "red"]) ︠047173b4-0ace-4d69-8b30-21d741c3147c︠ # Back to the start Z = one_tick(one_tick(one_tick(Z))) matrix_plot(Z, cmap=["white", "red"]) ︠fd01dbf1-fe4e-4c92-8560-5615745c6b91︠ # This uses python generators which we don't discuss until MCS275 # For now, it will iterate the one_tick function total number of times, # producing a list class GameOfLife: def __init__(self, total, board): self.board = board self.num = total def __iter__(self): return self def next(self): if self.num <= 0: raise StopIteration self.num -= 1 self.board = one_tick(self.board) return matrix_plot(self.board.copy(), cmap=["white", "red"]) ︠f92cb639-7692-4538-a849-080c434f0d5a︠ animate(GameOfLife(10, numpy.array([[0,0,0,0,0,0, 0, 0, 0], [0,0,0,1,0,0, 0, 0, 0], [0,1,0,1,0,0, 0, 0, 0], [0,0,1,1,0,0, 0, 0, 0], [0,0,0,0,0,0, 0, 0, 0], [0,0,0,0,0,0, 0, 0, 0], [0,0,0,0,0,0, 0, 0, 0], [0,0,0,0,0,0, 0, 0, 0], [0,0,0,0,0,0, 0, 0, 0]]))) ︠5aa7ba35-a991-4245-a256-6db1624153ff︠ # Here is the Gosper Glider Gun http://en.wikipedia.org/wiki/Gun_%28cellular_automaton%29 glider_gun = numpy.array([[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1], [0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1], [1,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [1,1,0,0,0,0,0,0,0,0,1,0,0,0,1,0,1,1,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]]) X = numpy.zeros((50, 70)) X[1:10,1:37] = glider_gun animate(GameOfLife(50, X)) ︠cf8fb8ef-91a1-471a-a2d9-ec94c09db656︠