15-110 PA9 Sample Solutions - Spring 2018 1. def display(c, matrix): # display current matrix of people on canvas c for row in range(0,len(matrix)): for col in range(0,len(matrix[row])): cell = matrix[row][col] if cell == 1: color = "yellow" else: color = "black" c.create_oval(25*col, 25*row, 25*col+25, 25*row+25, fill=color, outline="black") 2. def alive(matrix, row, col): return matrix[row][col] == 1 def dead(matrix, row, col): return matrix[row][col] == 0 def neighbors(matrix, row, col): # counts and returns number of live neighbors count = 0 if row-1 >= 0 and col-1 >= 0 and alive(matrix, row-1, col-1): count = count + 1 if row-1 >= 0 and alive(matrix, row-1, col): count = count + 1 if row-1 >= 0 and col+1 < len(matrix[row]) and alive(matrix, row-1, col+1): count = count + 1 if col-1 >= 0 and alive(matrix, row, col-1): count = count + 1 if col+1 < len(matrix[row]) and alive(matrix, row, col+1): count = count + 1 if row+1 < len(matrix) and col-1 >= 0 and alive(matrix, row+1, col-1): count = count + 1 if row+1 < len(matrix) and alive(matrix, row+1, col): count = count + 1 if row+1 < len(matrix) and col+1 < len(matrix[row]) and alive(matrix, row+1, col+1): count = count + 1 return count 3. def nextsecond(matrix): newmatrix = [] for i in range(len(matrix)): row = len(matrix[i]) * [0] newmatrix.append(row) for row in range(len(matrix)): for col in range(len(matrix[row])): count = neighbors(matrix, row, col) if alive(matrix, row, col): #underpopulation - death if count < 2: newmatrix[row][col] = 0 #overpopulation - death elif count > 3: newmatrix[row][col] = 0 #survival else: newmatrix[row][col] = 1 else: if count == 3: newmatrix[row][col] = 1 else: newmatrix[row][col] = 0 return newmatrix 4. def create_matrix(p): matrix = [] for i in range(0,30): row = [] for j in range(0,40): if randint(0,99) < p: row.append(1) else: row.append(0) matrix.append(row) return matrix def run_simulation2(init_seed, num_seconds, p): # create a canvas of size 1000 X 750 window = Tk() c = Canvas(window, width=1000, height=750) c.pack() seed(init_seed) matrix = create_matrix(p) display(c, matrix) c.update() sleep(2) for i in range(num_seconds): matrix = nextsecond(matrix) display(c, matrix) c.update() sleep(2) window.mainloop() # wait until user clicks close button return matrix