import pygame
import random
import sys
import time

# Ініціалізація
pygame.init()

# Вікно
WIDTH, HEIGHT = 800, 600
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Обійди Огородження")

# Кольори
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED   = (200, 0, 0)
GREEN = (0, 200, 0)
BLUE  = (0, 0, 255)
GRAY  = (100, 100, 100)

# Гравець
PLAYER_SIZE = 20
PLAYER_SPEED = 4

# Рівні
TOTAL_LEVELS = 5
START_POS = (50, 50)
GOAL_SIZE = 40
BORDER_WIDTH = 5

# Генерація перешкод
def generate_obstacles(level, goal_rect):
    obstacles = []
    attempts = 0
    max_obstacles = 10 + level * 5

    while len(obstacles) < max_obstacles and attempts < 500:
        w = random.randint(60, 150)
        h = random.randint(20, 60)
        x = random.randint(0 + BORDER_WIDTH, WIDTH - w - BORDER_WIDTH)
        y = random.randint(0 + BORDER_WIDTH, HEIGHT - h - BORDER_WIDTH)
        new_rect = pygame.Rect(x, y, w, h)

        start_rect = pygame.Rect(*START_POS, PLAYER_SIZE, PLAYER_SIZE)
        if new_rect.colliderect(start_rect) or new_rect.colliderect(goal_rect):
            attempts += 1
            continue

        if any(new_rect.colliderect(o) for o in obstacles):
            attempts += 1
            continue

        obstacles.append(new_rect)
        attempts = 0

    return obstacles

# Малювання всього
def draw_game(player, obstacles, goal, level, start_time):
    WIN.fill(WHITE)

    # Рамка по периметру
    pygame.draw.rect(WIN, GRAY, (0, 0, WIDTH, HEIGHT), BORDER_WIDTH)

    # Перешкоди, гравець, фініш
    pygame.draw.rect(WIN, GREEN, goal)
    for obs in obstacles:
        pygame.draw.rect(WIN, RED, obs)
    pygame.draw.rect(WIN, BLUE, player)

    # Рівень та таймер
    font = pygame.font.SysFont("consolas", 24)
    level_text = font.render(f"Рівень {level + 1}", True, BLACK)
    WIN.blit(level_text, (10, 10))

    elapsed_time = int(time.time() - start_time)
    timer_text = font.render(f"Час: {elapsed_time} с", True, BLACK)
    WIN.blit(timer_text, (WIDTH - 150, 10))

    pygame.display.update()

# Основна гра
def main():
    clock = pygame.time.Clock()
    level = 0
    player = pygame.Rect(*START_POS, PLAYER_SIZE, PLAYER_SIZE)
    start_time = time.time()

    while level < TOTAL_LEVELS:
        goal = pygame.Rect(WIDTH - GOAL_SIZE - 20, HEIGHT - GOAL_SIZE - 20, GOAL_SIZE, GOAL_SIZE)
        obstacles = generate_obstacles(level, goal)

        running = True
        while running:
            clock.tick(60)

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()

            # Рух
            keys = pygame.key.get_pressed()
            dx = dy = 0
            if keys[pygame.K_LEFT]: dx -= PLAYER_SPEED
            if keys[pygame.K_RIGHT]: dx += PLAYER_SPEED
            if keys[pygame.K_UP]: dy -= PLAYER_SPEED
            if keys[pygame.K_DOWN]: dy += PLAYER_SPEED

            next_pos = player.move(dx, dy)

            # Межі та рамка
            if (BORDER_WIDTH <= next_pos.left <= WIDTH - PLAYER_SIZE - BORDER_WIDTH and
                BORDER_WIDTH <= next_pos.top <= HEIGHT - PLAYER_SIZE - BORDER_WIDTH):
                if not any(next_pos.colliderect(obs) for obs in obstacles):
                    player = next_pos
                else:
                    player.topleft = START_POS
            else:
                player.topleft = START_POS

            if player.colliderect(goal):
                level += 1
                player.topleft = START_POS
                running = False

            draw_game(player, obstacles, goal, level, start_time)

    # Кінець гри
    WIN.fill(WHITE)
    font = pygame.font.SysFont("consolas", 48)
    final_time = int(time.time() - start_time)
    win_text = font.render("🎉 Ви пройшли гру!", True, BLACK)
    time_text = font.render(f"Час: {final_time} с", True, BLACK)
    WIN.blit(win_text, (WIDTH // 2 - win_text.get_width() // 2, HEIGHT // 2 - 60))
    WIN.blit(time_text, (WIDTH // 2 - time_text.get_width() // 2, HEIGHT // 2 + 10))
    pygame.display.update()
    pygame.time.delay(5000)
    pygame.quit()

if __name__ == "__main__":
    main()
