Игра жизнь - Код на Python
Conway's Game of Life implementation in Python
import random import time import os
def clear_screen(): # Clear screen command based on OS os.system('cls' if os.name == 'nt' else 'clear')
def create_grid(width, height): """Create a random initial grid""" return [[random.choice([0, 1]) for _ in range(width)] for _ in range(height)]
def print_grid(grid): """Print the current state of the grid""" for row in grid: print(''.join(['■' if cell else '□' for cell in row]))
def count_neighbors(grid, x, y): """Count the number of live neighbors for a cell""" height, width = len(grid), len(grid[0]) count = 0
# Check all 8 neighboring cells
for i in range(-1, 2):
for j in range(-1, 2):
if i == 0 and j == 0: # Skip the cell itself
continue
# Use modulo to wrap around the grid (toroidal)
neighbor_x, neighbor_y = (x + i) % width, (y + j) % height
count += grid[neighbor_y][neighbor_x]
return count
def next_generation(grid): """Calculate the next generation based on Conway's Game of Life rules""" height, width = len(grid), len(grid[0]) new_grid = [[0 for _ in range(width)] for _ in range(height)]
for y in range(height):
for x in range(width):
neighbors = count_neighbors(grid, x, y)
# Apply the rules of Conway's Game of Life
if grid[y][x] == 1: # Cell is alive
if neighbors < 2 or neighbors > 3:
new_grid[y][x] = 0 # Dies from underpopulation or overpopulation
else:
new_grid[y][x] = 1 # Survives
else: # Cell is dead
if neighbors == 3:
new_grid[y][x] = 1 # Becomes alive from reproduction
return new_grid
Main simulation
width, height = 20, 10 grid = create_grid(width, height)
Run 5 generations
for generation in range(5): clear_screen() print(f"Generation {generation + 1}") print_grid(grid) grid = next_generation(grid) time.sleep(1) # Pause to see each generation