import time from random import randint class GameOfLife: def __init__(self, rows, cols): self.rows = rows self.cols = cols self.grid = [[0 for _ in range(cols)] for _ in range(rows)] def set_alive(self, row, col): self.grid[row][col] = 1 def is_alive(self, row, col): return self.grid[row][col] == 1 def count_neighbors(self, row, col): count = 0 for r in range(max(row - 1, 0), min(row + 2, self.rows)): for c in range(max(col - 1, 0), min(col + 2, self.cols)): if (r, c) != (row, col) and self.is_alive(r, c): count += 1 return count def next_generation(self): new_grid = [[0 for _ in range(self.cols)] for _ in range(self.rows)] for r in range(self.rows): for c in range(self.cols): n = self.count_neighbors(r, c) if self.is_alive(r, c): if n < 2 or n > 3: new_grid[r][c] = 0 else: new_grid[r][c] = 1 else: if n == 3: new_grid[r][c] = 1 self.grid = new_grid def main(): rows = 15 cols = 15 game = GameOfLife(rows, cols) # Initialize with random live cells for i in range(rows*cols//4): game.set_alive(randint(0, rows-1), randint(0, cols-1)) # Main loop while True: for r in range(rows): for c in range(cols): if game.is_alive(r, c): display.pixel(r, c, 1) else: display.pixel(r, c, 0) game.next_generation() time.sleep(0.5) main()