"""
Урок 6: яблоко и рост.
Новое: функции, random, проверка "не на змейке", счёт.
Трюк роста: когда съели яблоко — НЕ убираем хвост, и змейка становится длиннее.
"""
import pygame, sys, random

CELL = 20
COLS, ROWS = 30, 20
WIDTH = CELL * COLS
HEIGHT = CELL * ROWS

BLACK = (30, 30, 46)
GREEN = (22, 196, 127)
DARK_GREEN = (0, 100, 0)
RED = (255, 107, 107)

pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Змейка")
clock = pygame.time.Clock()


def spawn_food(snake):
    """Случайная клетка, в которой НЕТ змейки."""
    while True:
        pos = (random.randint(0, COLS - 1), random.randint(0, ROWS - 1))
        if pos not in snake:
            return pos


snake = [(5, 10), (4, 10), (3, 10)]
direction = (1, 0)
food = spawn_food(snake)
score = 0

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP and direction != (0, 1):
                direction = (0, -1)
            elif event.key == pygame.K_DOWN and direction != (0, -1):
                direction = (0, 1)
            elif event.key == pygame.K_LEFT and direction != (1, 0):
                direction = (-1, 0)
            elif event.key == pygame.K_RIGHT and direction != (-1, 0):
                direction = (1, 0)

    head_x, head_y = snake[0]
    new_head = (head_x + direction[0], head_y + direction[1])
    snake.insert(0, new_head)

    # Съели яблоко? Растём — хвост НЕ убираем.
    if new_head == food:
        score += 1
        food = spawn_food(snake)
        pygame.display.set_caption(f"Змейка — {score}")
    else:
        snake.pop()

    screen.fill(BLACK)

    # Яблоко
    food_rect = pygame.Rect(food[0] * CELL, food[1] * CELL, CELL, CELL)
    pygame.draw.rect(screen, RED, food_rect)

    # Змейка
    head_rect = pygame.Rect(snake[0][0] * CELL, snake[0][1] * CELL, CELL, CELL)
    pygame.draw.rect(screen, GREEN, head_rect)
    for segment in snake[1:]:
        rect = pygame.Rect(segment[0] * CELL, segment[1] * CELL, CELL, CELL)
        pygame.draw.rect(screen, DARK_GREEN, rect)

    pygame.display.flip()
    clock.tick(10)
