import random
import pygame
Размер экрана
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
Размер клетки
CELL_SIZE = 20
Цвета
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
YELLOW = (255, 255, 0)
BLUE = (0, 0, 255)
Класс клетки
class Cell:
def init(self, x, y, color=WHITE):
self.x = x
self.y = y
self.color = color
self.is_alive = False
self.age = 0
self.is_mutant = False
def draw(self, surface):
pygame.draw.rect(surface, self.color, (self.x * CELL_SIZE, self.y * CELL_SIZE, CELL_SIZE, CELL_SIZE))
def update(self, board):
neighbors = 0
for i in range(-1, 2):
for j in range(-1, 2):
if i == 0 and j == 0:
continue
x = self.x + i
y = self.y + j
if x < 0 or y < 0 or x >= len(board) or y >= len(board[0]):
continue
if board[x][y].is_alive:
neighbors += 1
if self.is_alive:
if neighbors < 2 or neighbors > 3:
self.is_alive = False
self.color = WHITE
else:
self.age += 1
if self.age >= 3:
self.age = self.age % 3
self.produce_offspring(board)
else:
if neighbors == 3:
self.is_alive = True
self.color = GREEN
def produce_offspring(self, board):
for i in range(-1, 2):
for j in range(-1, 2):
if i == 0 and j == 0:
continue
x = self.x + i
y = self.y + j
if x < 0 or y < 0 or x >= len(board) or y >= len(board[0]):
continue
if not board[x][y].is_alive:
if random.random() < 0.2:
board[x][y].is_mutant = True
board[x][y].color = BLUE
else:
board[x][y].is_mutant = False
board[x][y].color = YELLOW
Создание доски
board = [[Cell(i, j) for j in range(SCREEN_HEIGHT // CELL_SIZE)] for i in range(SCREEN_WIDTH // CELL_SIZE)]
Инициализация pygame
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
clock = pygame.time.Clock()
Главный цикл игры
while True:
# Обработка событий
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
# Обновление клеток
for row in board:
for cell in row:
cell.update(board)
# Отрисовка клеток
screen.fill(BLACK)
for row in board:
for cell in row:
cell.draw(screen)
pygame.display.update()
# Ограничение частоты кадров
clock.tick(10)