import random
import pygame
import json
import os


WIDTH = 1266
HEIGHT = 668
FPS = 85
BLOCK_SIZE = 15
SAVE_FILE = "Baza.json"

# --- ЦВЕТА ---
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
yellow = (245, 130, 0)


pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("зМеЕнЫшЬ")
clock = pygame.time.Clock()



class Player(pygame.sprite.Sprite):
    def __init__(self, load_from_save=False):
        super().__init__()
        self.image = pygame.Surface((BLOCK_SIZE, BLOCK_SIZE))
        self.image.fill(green)
        self.rect = self.image.get_rect()

        if load_from_save and os.path.exists(SAVE_FILE):
            self.load_game()
        else:
            self.rect.x = WIDTH // 2
            self.rect.y = HEIGHT // 2
            self.dx = 0
            self.dy = 0
            self.body = []
            self.length = 1
            self.score = 0
            self.speed = 15

    def update(self):

        self.rect.x += self.dx
        self.rect.y += self.dy


        self.body.append([self.rect.x, self.rect.y])


        if len(self.body) > self.length:
            del self.body[0]


        for segment in self.body[:-1]:
            if segment[0] == self.rect.x and segment[1] == self.rect.y:
                return False
        return True

    def draw_body(self, surface):
        for segment in self.body[:-1]:
            pygame.draw.rect(surface, green, [segment[0], segment[1], BLOCK_SIZE, BLOCK_SIZE])

    def grow(self):
        self.length += 1
        self.score += 1

    def save_game(self):

        save_data = {
            'head_x': self.rect.x,
            'head_y': self.rect.y,
            'dx': self.dx,
            'dy': self.dy,
            'body': self.body,
            'length': self.length,
            'score': self.score,
            'speed': self.speed
        }
        with open(SAVE_FILE, 'w') as f:
            json.dump(save_data, f)
        print("Игра сохранена!")

    def load_game(self):

        try:
            with open(SAVE_FILE, 'r') as f:
                save_data = json.load(f)

            self.rect.x = save_data['head_x']
            self.rect.y = save_data['head_y']
            self.dx = save_data['dx']
            self.dy = save_data['dy']
            self.body = save_data['body']
            self.length = save_data['length']
            self.score = save_data['score']
            self.speed = save_data['speed']

            if len(self.body) > self.length:
                self.body = self.body[-self.length:]
            elif len(self.body) < self.length:
                while len(self.body) < self.length:
                    self.body.append(self.body[-1].copy())

            print("Игра загружена! Счёт:", self.score)
        except Exception as e:
            print(f"Ошибка загрузки: {e}")
            self.rect.x = WIDTH // 2
            self.rect.y = HEIGHT // 2
            self.dx = 0
            self.dy = 0
            self.body = []
            self.length = 1
            self.score = 0
            self.speed = 15


class Meat(pygame.sprite.Sprite):
    def __init__(self, player_body=None):
        super().__init__()
        self.image = pygame.Surface((BLOCK_SIZE, BLOCK_SIZE))
        self.image.fill(red)
        self.rect = self.image.get_rect()
        self.respawn(player_body)

    def respawn(self, player_body=None):
        self.rect.x = random.randrange(0, WIDTH - BLOCK_SIZE, BLOCK_SIZE)
        self.rect.y = random.randrange(0, HEIGHT - BLOCK_SIZE, BLOCK_SIZE)

        if player_body:
            while any(
                    self.rect.colliderect(pygame.Rect(seg[0], seg[1], BLOCK_SIZE, BLOCK_SIZE)) for seg in player_body):
                self.rect.x = random.randrange(0, WIDTH - BLOCK_SIZE, BLOCK_SIZE)
                self.rect.y = random.randrange(0, HEIGHT - BLOCK_SIZE, BLOCK_SIZE)


all_sprites = pygame.sprite.Group()
meats = pygame.sprite.Group()

load_exists = os.path.exists(SAVE_FILE)
player = Player(load_from_save=load_exists)
meat = Meat(player.body if load_exists else None)

all_sprites.add(player)
all_sprites.add(meat)
meats.add(meat)


running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_r:
                player.save_game()

            if event.key == pygame.K_w and player.dy == 0:
                player.dy = -BLOCK_SIZE
                player.dx = 0
            elif event.key == pygame.K_s and player.dy == 0:
                player.dy = BLOCK_SIZE
                player.dx = 0
            elif event.key == pygame.K_a and player.dx == 0:
                player.dx = -BLOCK_SIZE
                player.dy = 0
            elif event.key == pygame.K_d and player.dx == 0:
                player.dx = BLOCK_SIZE
                player.dy = 0

    if not player.update():
        running = False

    if (player.rect.x < 0 or player.rect.x >= WIDTH or
            player.rect.y < 0 or player.rect.y >= HEIGHT):
        running = False

    if pygame.sprite.spritecollide(player, meats, True):
        player.grow()

        new_meat = Meat(player.body)

        while any(
                new_meat.rect.colliderect(pygame.Rect(seg[0], seg[1], BLOCK_SIZE, BLOCK_SIZE)) for seg in player.body):
            new_meat.respawn(player.body)

        all_sprites.add(new_meat)
        meats.add(new_meat)

    screen.fill(black)


    all_sprites.draw(screen)


    player.draw_body(screen)


    font = pygame.font.SysFont("Arial", 25)
    score_text = font.render(f"Счёт: {player.score}", True, white)
    screen.blit(score_text, [10, 10])


    save_hint = font.render("Нажми R для сохранения", True, white)
    screen.blit(save_hint, [10, HEIGHT - 30])

    pygame.display.flip()

    clock.tick(player.speed)

pygame.quit()













"""import random
import pygame
import json

# --- КОНФИГУРАЦИЯ ---
WIDTH = 1266
HEIGHT = 668
FPS = 85
BLOCK_SIZE = 15  # Размер блока змейки и еды

# --- ЦВЕТА ---
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
yellow = (245, 130, 0)

# --- ИНИЦИАЛИЗАЦИЯ PYGAME ---
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("зМеЕнЫшЬ")
clock = pygame.time.Clock()

# --- КЛАСС ИГРОКА (ЗМЕЙКА) ---
class Player(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.Surface((BLOCK_SIZE, BLOCK_SIZE))
        self.image.fill(green)
        self.rect = self.image.get_rect()
        self.rect.x = WIDTH // 2
        self.rect.y = HEIGHT // 2
        self.dx = 0
        self.dy = 0
        self.body = []
        self.length = 1
        self.score = 0
        self.speed = 15

    def update(self):
        # Движение головы
        self.rect.x += self.dx
        self.rect.y += self.dy

        # Добавляем новую позицию головы в тело
        self.body.append([self.rect.x, self.rect.y])

        # Если тело длиннее допустимого, удаляем хвост
        if len(self.body) > self.length:
            del self.body[0]

        # Проверка столкновения с собственным телом
        for segment in self.body[:-1]:
            if segment[0] == self.rect.x and segment[1] == self.rect.y:
                return False  # Игра окончена
        return True  # Продолжаем игру

    def draw_body(self, surface):
        for segment in self.body[:-1]:  # Рисуем всё тело, кроме головы (голова — это спрайт)
            pygame.draw.rect(surface, green, [segment[0], segment[1], BLOCK_SIZE, BLOCK_SIZE])

    def grow(self):
        self.length += 1
        
<-- Это ШИЗОФРЕНИЯ
        
        self.score += 1


# --- КЛАСС ЕДЫ ---
class Meat(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.Surface((BLOCK_SIZE, BLOCK_SIZE))
        self.image.fill(red)
        self.rect = self.image.get_rect()
        self.respawn()

    def respawn(self):
        # Генерация еды только в координатах, кратных размеру блока
        self.rect.x = random.randrange(0, WIDTH - BLOCK_SIZE, BLOCK_SIZE)
        self.rect.y = random.randrange(0, HEIGHT - BLOCK_SIZE, BLOCK_SIZE)


# --- СОЗДАНИЕ ГРУПП И ОБЪЕКТОВ ---
all_sprites = pygame.sprite.Group()
meats = pygame.sprite.Group()

with open('Baza.json', 'r', encoding='utf-8') as f:
    dataR = json.load(f)

player = Player()
player.body = dataR["Body"]
player.length = dataR["Length"]
player.score = dataR["Score"]
meat = Meat()

all_sprites.add(player)
all_sprites.add(meat)
meats.add(meat)

# --- ГЛАВНЫЙ ИГРОВОЙ ЦИКЛ ---
running = True
while running:
    # --- ОБРАБОТКА СОБЫТИЙ ---
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        if event.type == pygame.KEYDOWN:
            # Управление (запрет движения назад на себя)
            if event.key == pygame.K_w and player.dy == 0:
                player.dy = -BLOCK_SIZE
                player.dx = 0
            elif event.key == pygame.K_s and player.dy == 0:
                player.dy = BLOCK_SIZE
                player.dx = 0
            elif event.key == pygame.K_a and player.dx == 0:
                player.dx = -BLOCK_SIZE
                player.dy = 0
            elif event.key == pygame.K_d and player.dx == 0:
                player.dx = BLOCK_SIZE
                player.dy = 0
            elif event.key == pygame.K_r:
                data = {
                    "Body": player.body,
                    "Length": player.length,
                    "Score": player.score
                }
            elif event.key == pygame.K_c:
                data = {
                    "Body": [],
                    "Length": 1,
                    "Score": 0
                }

    # --- ОБНОВЛЕНИЕ ЛОГИКИ ---
    if not player.update():  # Проверка столкновения с собой
        running = False

    # Проверка выхода за границы экрана
    if (player.rect.x < 0 or player.rect.x >= WIDTH or
            player.rect.y < 0 or player.rect.y >= HEIGHT):
        running = False

    # Проверка поедания еды (столкновение спрайтов)
    if pygame.sprite.spritecollide(player, meats, True):
        player.grow()

        new_meat = Meat()

        # Проверка: не появилась ли еда внутри тела змейки (опционально для честности)
        while any(
                new_meat.rect.colliderect(pygame.Rect(seg[0], seg[1], BLOCK_SIZE, BLOCK_SIZE)) for seg in player.body):
            new_meat.respawn()

        all_sprites.add(new_meat)
        meats.add(new_meat)

    # --- ОТРИСОВКА ---
    screen.fill(black)  # Заливка фона черным

    # Отрисовка всех спрайтов (еда и голова змейки)
    all_sprites.draw(screen)

    # Отрисовка тела змейки (которое не является спрайтом)
    player.draw_body(screen)

    # Отрисовка счета в углу экрана
    font = pygame.font.SysFont("Arial", 25)
    score_text = font.render(f"Счёт: {player.score}", True, white)
    screen.blit(score_text, [10, 10])

    pygame.display.flip()  # Обновление экрана

    clock.tick(player.speed)  # Ограничение FPS

pygame.quit() """