The core problem to be solved in the implementation of the Game of Life is how t
ID: 3866001 • Letter: T
Question
The core problem to be solved in the implementation of the Game of Life is how to generate the next grid from the current grid. Your task is to write a function called nextGen which expects only one argument. That argument is a two-dimensional table (i.e., a list of lists) with m rows and n columns, representing the current grid. The elements of the table are either 0 (empty square) or 1 (occupied square). You may assume that all rows have the same number of elements. Given the current grid, nextGen computes and returns (but does not print) a new next grid (without altering the current grid) by applying the simple rules provided above. For example, given this initial grid: glider = [[0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0. 0], [0, 0, 0, 1, 0, 0, 0], [0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]] your function should work like this: > > > x = nextGen (glider) > > > x [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0,0, 0], [0, 1, 0, 1,0, 0, 0], [0, 0, 1, 1, 0. 0. 0], [0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]] > > > y = nextGen (x) > > > y [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0,1, 0, 1, 0. 0, 0], [0, 0, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]] > > > z nextGen (y) > > > z[[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 1, 1, 0,0], [0, 0, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]] > > > q = nextGen (z) > > > q [[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, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0. 0. 0]]Explanation / Answer
def play_life(a): xmax = len(a) ymax = len(a[0]) b = [[cell for cell in row] for row in life] for x in range(xmax): for y in range(ymax): n = 0 for i in range(max(x - 1, 0), min(x + 2, xmax)): for j in range(max(y - 1, 0), min(y + 2, ymax)): n += a[i][j] n -= a[x][y] if a[x][y]: if n < 2 or n > 3: b[x][y] = 0 # living cells with 3 neighbors die elif n == 3: b[x][y] = 1 # dead cells with 3 neighbors ar born return(b) # this function just prints the board def show_life(a): print(' '.join([' '.join([str(cell) for cell in row]) for row in life]) + ' ') # create board x_size, y_size = (5, 5) life = [[0 for y in range(y_size)] for x in range(x_size)] # place starting conditions here for x in range(1, 4): life[x][2] = 1 # middle three in middle row to 1 # now let's play show_life(life) for i in range(3): life = play_life(life) show_life(life)Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.