import pygame
import random
import time
from Apple import Apple
from Snake import Snake
from Direction import Direction

SCREEN_WIDTH = 800
SCREEN_HEIGTH = 608 
punkty = 0

#tworzenie tła
background = pygame.Surface((SCREEN_WIDTH,SCREEN_HEIGTH))

for i in range(25):
    for j in range(19):
        image = pygame.image.load("images/background.png")
        mask = (random.randrange(0,20),random.randrange(0,20),random.randrange(0,20))
        #zlewamy maskę z konkretnym kafelkiem, aby zmienić minilallnie kolor
        image.fill(mask, special_flags=pygame.BLEND_ADD)
        #rozmier kafelka 32x32
        background.blit(image,(i*32,j*32))

pygame.init()
screen = pygame.display.set_mode([SCREEN_WIDTH,SCREEN_HEIGTH])
clock = pygame.time.Clock()
#obiekt czcionki
my_font = pygame.font.SysFont("Comic Sans MS", 24)
#Tworzenie snaka 
snake = Snake()
MOVE_SNAKE = pygame.USEREVENT + 1 
pygame.time.set_timer(MOVE_SNAKE,200)
appleGroup = pygame.sprite.Group()
for i in range(150):
    apple = Apple()
    appleGroup.add(apple)

isGameWorks = True

while isGameWorks: 
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                isGameWorks = False
            if event.key == pygame.K_w:
                snake.chanege_direction(Direction.UP)
            if event.key == pygame.K_s:
                snake.chanege_direction(Direction.DOWN)
            if event.key == pygame.K_d:
                snake.chanege_direction(Direction.RIGHT)
            if event.key == pygame.K_a:
                snake.chanege_direction(Direction.LEFT)

        elif event.type == pygame.QUIT:
            isGameWorks = False        
        elif event.type == MOVE_SNAKE:
            snake.update()



    #sprawdzanie czy głowa weza jest na jabko
        collision_with_apple = pygame.sprite.spritecollideany(snake, appleGroup)
        if collision_with_apple != None:
            collision_with_apple.kill()
            snake.eat_apple()
            punkty += 1 
            apple = Apple()
            appleGroup.add(apple)
    
    #rysowanie tła
    screen.blit(background,(0,0))
    #rysowanie segmentów
    snake.draw_segments(screen)
    #rysowanie glowy weza 
    screen.blit(snake.image, snake.rect)
    #rysowanie jabłek 
    for apple in appleGroup:
        screen.blit(apple.image, apple.rect)
    #wyswietlanie wyniku
    score_text = my_font.render(f"wynik: {punkty}", False, (0,0,0))
    screen.blit(score_text,(16,16))
    if snake.check_collision():
        game_over_text = my_font.render(f"Przegrana!!!!!!!: {punkty}", False, (200,0,0))
        screen.blit(game_over_text,(SCREEN_WIDTH/2-50, SCREEN_HEIGTH/2))
        isGameWorks = False

    #wyczyszcenie ekranu 
    pygame.display.flip()
    #ustawienie stałego fps 30 
    clock.tick(30)

time.sleep(3)
pygame.quit()