# cython: language_level=3 # L-15 MCS 507 Mon 25 Sep 2023 : run_game_of_life.pyx """ This files defines Cython code for the module run_game_of_life to export methods to update the matrix as in the game of life of John Conway. With type declarations we hope to achieve fast access. """ import numpy as np cimport numpy as np ctypedef np.uint8_t dtype_t def neighbors(np.ndarray[dtype_t, ndim=2] alive, Py_ssize_t i, Py_ssize_t j): """ Returns number of cells alive next to alive[i, j]. """ cdef dtype_t cnt = 0 if(i > 0): if alive[i-1, j]: cnt = cnt + 1 if j > 0: if alive[i-1, j-1]: cnt = cnt + 1 if(j < alive.shape[1]-1): if alive[i-1, j+1]: cnt = cnt + 1 if(i < alive.shape[0]-1): if alive[i+1, j]: cnt = cnt + 1 if(j > 0): if alive[i+1,j-1]: cnt = cnt + 1 if(j < alive.shape[1]-1): if alive[i+1,j+1]: cnt = cnt + 1 if(j > 0): if alive[i, j-1]: cnt = cnt + 1 if(j < alive.shape[1]-1): if alive[i, j+1]: cnt = cnt + 1 return cnt def update(np.ndarray[dtype_t, ndim=2] alive): """ Applies the rules of Conway's game of life. """ cdef Py_ssize_t i, j cdef np.ndarray[dtype_t, ndim=2] result cdef dtype_t nbn result = np.zeros((alive.shape[0], alive.shape[1]), np.uint8) for i in range(0, alive.shape[0]): for j in range(0, alive.shape[1]): nbn = neighbors(alive, i, j) if(alive[i, j] == 1): if((nbn < 2) or (nbn > 3)): result[i, j] = 0 else: result[i, j] = 1 else: if(nbn == 3): result[i, j] = 1 return result