import pygame
import random
import sys

# --- Инициализация Pygame ---
pygame.init()

# --- Константы игры ---
WIDTH, HEIGHT = 600, 400  # Размер окна
SNAKE_SIZE = 20            # Размер одной клетки (и змейки)
SNAKE_WIDTH = WIDTH // SNAKE_SIZE
SNAKE_HEIGHT = HEIGHT // SNAKE_SIZE

# Цвета
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)

# Направления
UP = (0, -1)
DOWN = (0, 1)
LEFT = (-1, 0)
RIGHT = (1, 0)

# --- Настройка экрана ---
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Змейка с врагами")
clock = pygame.time.Clock()
font = pygame.font.SysFont('Arial', 25)

def draw_text(surface, text, color, x, y):
    """Вспомогательная функция для отрисовки текста на экране."""
    text_obj = font.render(text, True, color)
    text_rect = text_obj.get_rect()
    text_rect.topleft = (x, y)
    surface.blit(text_obj, text_rect)

class Snake:
    def __init__(self):
        self.length = 1
        self.positions = [((WIDTH // 2), (HEIGHT // 2))] # Старт в центре
        self.direction = random.choice([UP, DOWN, LEFT, RIGHT])
        self.color = GREEN

    def get_head_position(self):
        return self.positions[0]

    def turn(self, point):
        # Запрет разворота на 180 градусов
        if (point[0] * -1, point[1] * -1) == self.direction:
            return
        self.direction = point

    def move(self):
        cur = self.get_head_position()
        x, y = self.direction
        new = (((cur[0] + (x * SNAKE_SIZE)) % WIDTH), (cur[1] + (y * SNAKE_SIZE)) % HEIGHT)

        # Проверка на столкновение с собой
        if len(self.positions) > 2 and new in self.positions[2:]:
            self.reset()
            return

        self.positions.insert(0, new)
        if len(self.positions) > self.length:
            self.positions.pop()

    def reset(self):
        """Сброс игры при смерти."""
        self.length = 1
        self.positions = [((WIDTH // 2), (HEIGHT // 2))]
        self.direction = random.choice([UP, DOWN, LEFT, RIGHT])

    def draw(self, surface):
        for p in self.positions:
            r = pygame.Rect((p[0], p[1]), (SNAKE_SIZE, SNAKE_SIZE))
            pygame.draw.rect(surface, self.color, r)
            pygame.draw.rect(surface, WHITE, r, 1) # Обводка

    def handle_keys(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP:
                    self.turn(UP)
                elif event.key == pygame.K_DOWN:
                    self.turn(DOWN)
                elif event.key == pygame.K_LEFT:
                    self.turn(LEFT)
                elif event.key == pygame.K_RIGHT:
                    self.turn(RIGHT)

class Food:
    def __init__(self):
        self.position = (0, 0)
        self.color = RED
        self.randomize_position()

    def randomize_position(self):
        """Ставит еду в случайное место на сетке."""
        self.position = (random.randint(0, SNAKE_WIDTH-1) * SNAKE_SIZE,
                         random.randint(0, SNAKE_HEIGHT-1) * SNAKE_SIZE)

    def draw(self, surface):
        r = pygame.Rect((self.position[0], self.position[1]), (SNAKE_SIZE-1, SNAKE_SIZE-1))
        pygame.draw.rect(surface, self.color, r)

class Enemy:
    def __init__(self):
        self.position = (random.randint(0, SNAKE_WIDTH-1) * SNAKE_SIZE,
                         random.randint(0, SNAKE_HEIGHT-1) * SNAKE_SIZE)
        self.color = BLUE
        self.direction = random.choice([UP, DOWN, LEFT, RIGHT])

    def move(self):
        """Двигается в текущем направлении. Меняет его при столкновении со стеной."""
        x_dir, y_dir = self.direction
        new_x = (self.position[0] + x_dir * SNAKE_SIZE) % WIDTH
        new_y = (self.position[1] + y_dir * SNAKE_SIZE) % HEIGHT

        # Проверка на столкновение со стеной для смены направления
        if new_x < 0 or new_x >= WIDTH or new_y < 0 or new_y >= HEIGHT:
            self.direction = random.choice([UP, DOWN, LEFT, RIGHT])
            return

        self.position = (new_x, new_y)

    def draw(self, surface):
        r = pygame.Rect((self.position[0], self.position[1]), (SNAKE_SIZE-1, SNAKE_SIZE-1))
        pygame.draw.rect(surface, self.color, r)


def main():
    snake = Snake()
    food = Food()
    enemies = [Enemy() for _ in range(3)] # Создаем 3 врага
    score = 0

    while True:
        clock.tick(15) # Скорость игры

        snake.handle_keys() # Обработка ввода и событий

        snake.move()

        # --- Логика игры ---

        # Проверка столкновения с едой
        if snake.get_head_position() == food.position:
            snake.length += 1
            score += 1
            food.randomize_position()

            # Увеличиваем сложность: добавляем врага каждые 3 очка
            if score % 3 == 0 and score != 0:
                enemies.append(Enemy())

        # Двигаем врагов и проверяем столкновение со змейкой
        head_pos = snake.get_head_position()
        for enemy in enemies[:]: # Используем срез для безопасного удаления из списка во время итерации
            enemy.move()
            if enemy.position == head_pos:
                snake.reset()
                score = 0
                enemies.clear() # Убираем всех врагов при смерти и пересоздаем начальное количество
                enemies.extend([Enemy() for _ in range(3)])
                break

        # --- Отрисовка ---

        screen.fill(BLACK) # Заливаем фон черным

        snake.draw(screen)
        food.draw(screen)

        for enemy in enemies:
            enemy.draw(screen)

        # Отрисовка счетчика и кол-ва врагов в углу экрана
        draw_text(screen, f"Счет: {score}", WHITE, 5, 5)
        draw_text(screen, f"Враги: {len(enemies)}", WHITE, WIDTH - 120, 5)

        pygame.display.update()


if __name__ == "__main__":
    main()