Generates the next generation for a given state of Conway's Game of Life. >>> new_generation(BLINKER) [[0, 0, 0], [1, 1, 1], [0, 0, 0]]
(cells: list[list[int]])
| 24 | |
| 25 | |
| 26 | def new_generation(cells: list[list[int]]) -> list[list[int]]: |
| 27 | """ |
| 28 | Generates the next generation for a given state of Conway's Game of Life. |
| 29 | >>> new_generation(BLINKER) |
| 30 | [[0, 0, 0], [1, 1, 1], [0, 0, 0]] |
| 31 | """ |
| 32 | next_generation = [] |
| 33 | for i in range(len(cells)): |
| 34 | next_generation_row = [] |
| 35 | for j in range(len(cells[i])): |
| 36 | # Get the number of live neighbours |
| 37 | neighbour_count = 0 |
| 38 | if i > 0 and j > 0: |
| 39 | neighbour_count += cells[i - 1][j - 1] |
| 40 | if i > 0: |
| 41 | neighbour_count += cells[i - 1][j] |
| 42 | if i > 0 and j < len(cells[i]) - 1: |
| 43 | neighbour_count += cells[i - 1][j + 1] |
| 44 | if j > 0: |
| 45 | neighbour_count += cells[i][j - 1] |
| 46 | if j < len(cells[i]) - 1: |
| 47 | neighbour_count += cells[i][j + 1] |
| 48 | if i < len(cells) - 1 and j > 0: |
| 49 | neighbour_count += cells[i + 1][j - 1] |
| 50 | if i < len(cells) - 1: |
| 51 | neighbour_count += cells[i + 1][j] |
| 52 | if i < len(cells) - 1 and j < len(cells[i]) - 1: |
| 53 | neighbour_count += cells[i + 1][j + 1] |
| 54 | |
| 55 | # Rules of the game of life (excerpt from Wikipedia): |
| 56 | # 1. Any live cell with two or three live neighbours survives. |
| 57 | # 2. Any dead cell with three live neighbours becomes a live cell. |
| 58 | # 3. All other live cells die in the next generation. |
| 59 | # Similarly, all other dead cells stay dead. |
| 60 | alive = cells[i][j] == 1 |
| 61 | if (alive and 2 <= neighbour_count <= 3) or ( |
| 62 | not alive and neighbour_count == 3 |
| 63 | ): |
| 64 | next_generation_row.append(1) |
| 65 | else: |
| 66 | next_generation_row.append(0) |
| 67 | |
| 68 | next_generation.append(next_generation_row) |
| 69 | return next_generation |
| 70 | |
| 71 | |
| 72 | def generate_images(cells: list[list[int]], frames: int) -> list[Image.Image]: |
no test coverage detected