import pygame
import random

HEIGHT = 600
WIDTH = 600
FPS = 60

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
MediumSlateBlue = (123, 104, 238)
MediumOrchid = (186, 85, 211)
GREEN = (0, 255, 0)  # Цвет зеленого цвета был неправильно задан ранее
ORANGE = (255, 123, 0)
# Основная логика игры
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Levumpa's Game")
clock = pygame.time.Clock()
player_block = 3
player_speed = 3



class Player(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.Surface((50,40))
        self.image.fill(MediumOrchid )
        self.rect = self.image.get_rect()
        self.rect.x = 400
        self.rect.y = 300
        self.dx = 0
        self.dy = 0
        self.score = 0


    def update(self):
        self.rect.x += self.dx
        self.rect.y += self.dy

class Apple(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.Surface((50,40))
        self.image.fill(RED)
        self.rect = self.image.get_rect()
        self.respawn()

    def respawn(self):
        self.rect.x = random.randrange(0,600 - player_block, player_block)
        self.rect.y = random.randrange(0, 600 - player_block, player_block)


all_sprites = pygame.sprite.Group()
foods = pygame.sprite.Group()

player = Player()
food = Apple()
all_sprites.add(player, food)

foods.add(food)


score = 0
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_LEFT and player.dx == 0:
                player.dx =-player_block
                player.dy = 0
            elif event.key == pygame.K_RIGHT and player.dx == 0:
                player.dx = player_block
                player.dy = 0
            elif event.key == pygame.K_UP and player.dy == 0:
                player.dy =-player_block
                player.dx = 0
            elif event.key == pygame.K_DOWN and player.dy == 0:
                player.dy = player_block
                player.dx = 0


    if (player.rect.x < 0 or player.rect.x >= 600 or player.rect.y < 0 or player.rect.y >= 600):
        running = False

    if pygame.sprite.spritecollide(player, foods, True):
        new_food = Apple()
        all_sprites.add(new_food)
        foods.add(new_food)
        score += 1




    # Обновляем положение всех спрайтов
    all_sprites.update()

    # Отрисовка фона и всех спрайтов
    screen.fill(MediumSlateBlue)

    font = pygame.font.SysFont("bahnschrift",25)
    score_text = font.render(f"Счёт: {score}", True,BLACK)
    screen.blit(score_text,[10,10])

    all_sprites.draw(screen)
    clock.tick(FPS)
    pygame.display.flip()

pygame.quit()