import pygame
import random
import time
import math

# Инициализация Pygame
pygame.init()

# Настройки экрана
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Clash of Clones")

# Цвета
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

# Настройки игры
clock = pygame.time.Clock()
FPS = 30

# Игровые переменные
base_health = 100
base_level = 1
base_upgrade_cost = 50
resources = 100
enemy_spawn_time = 3  # 3 секунды для примера спавна врагов
last_enemy_spawn = time.time()
tower_cost = 30

# Определение башен
class Tower:
    def __init__(self, x, y, damage, range):
        self.x = x
        self.y = y
        self.width = 40
        self.height = 40
        self.range = range
        self.damage = damage
        self.level = 1  # Уровень башни

    def draw(self):
        pygame.draw.rect(screen, GREEN, (self.x, self.y, self.width, self.height))

    def attack(self, enemies):
        for enemy in enemies:
            distance = math.sqrt((self.x - enemy.x) ** 2 + (self.y - enemy.y) ** 2)
            if distance <= self.range:
                enemy.health -= self.damage
                if enemy.health <= 0:
                    enemies.remove(enemy)
                break

# Класс для базы
class Base:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.width = 100
        self.height = 100

    def draw(self):
        pygame.draw.rect(screen, BLUE, (self.x, self.y, self.width, self.height))

# Класс для врагов
class Enemy:
    def __init__(self):
        self.x = random.randint(0, screen_width)
        self.y = 0
        self.width = 50
        self.height = 50
        self.speed = random.randint(1, 3)
        self.health = 10

    def draw(self):
        pygame.draw.rect(screen, RED, (self.x, self.y, self.width, self.height))

    def move(self):
        self.y += self.speed

# Списки врагов и башен
enemies = []
towers = []

# Функция для отображения главного меню
def main_menu():
    while True:
        screen.fill(WHITE)
        font = pygame.font.SysFont(None, 55)
        title_text = font.render("Clash of Clones", True, BLACK)
        start_text = font.render("Press ENTER to Start", True, BLACK)
        exit_text = font.render("Press ESC to Exit", True, BLACK)
        screen.blit(title_text, (screen_width // 2 - 150, screen_height // 2 - 50))
        screen.blit(start_text, (screen_width // 2 - 180, screen_height // 2 + 20))
        screen.blit(exit_text, (screen_width // 2 - 150, screen_height // 2 + 80))
        
        pygame.display.flip()
        
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RETURN:
                    return  # Переход к игре
                if event.key == pygame.K_ESCAPE:
                    pygame.quit()
                    quit()

# Функция выбора башен
def tower_selection():
    selected_tower = None
    while True:
        screen.fill(WHITE)
        font = pygame.font.SysFont(None, 55)
        title_text = font.render("Select Your Tower", True, BLACK)
        tower1_text = font.render("1: Basic Tower (Damage: 5, Range: 100)", True, BLACK)
        tower2_text = font.render("2: Advanced Tower (Damage: 10, Range: 150)", True, BLACK)
        tower3_text = font.render("3: Sniper Tower (Damage: 15, Range: 200)", True, BLACK)
        back_text = font.render("Press B to go Back", True, BLACK)

        screen.blit(title_text, (screen_width // 2 - 180, screen_height // 2 - 100))
        screen.blit(tower1_text, (50, screen_height // 2 - 30))
        screen.blit(tower2_text, (50, screen_height // 2 + 20))
        screen.blit(tower3_text, (50, screen_height // 2 + 70))
        screen.blit(back_text, (50, screen_height - 100))

        pygame.display.flip()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_1:
                    selected_tower = Tower(0, 0, 5, 100)  # Базовая башня
                    return selected_tower
                elif event.key == pygame.K_2:
                    selected_tower = Tower(0, 0, 10, 150)  # Улучшенная башня
                    return selected_tower
                elif event.key == pygame.K_3:
                    selected_tower = Tower(0, 0, 15, 200)  # Снайперская башня
                    return selected_tower
                elif event.key == pygame.K_b:
                    return None  # Возврат в главное меню

# Основной игровой цикл
def game_loop():
    global resources, base_health, last_enemy_spawn
    base_health = 100
    resources = 100
    last_enemy_spawn = time.time()
    global towers, enemies

    while True:
        clock.tick(FPS)
        screen.fill(WHITE)

        # Отображение базы
        base = Base(screen_width // 2 - 50, screen_height - 150)
        base.draw()

        # Обработка событий
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
            if event.type == pygame.MOUSEBUTTONDOWN:
                x, y = event.pos
                tower = tower_selection()
                if tower:
                    tower.x = x - tower.width // 2
                    tower.y = y - tower.height // 2
                    towers.append(tower)

        # Спавн врагов
        if time.time() - last_enemy_spawn > enemy_spawn_time:
            enemies.append(Enemy())
            last_enemy_spawn = time.time()

        # Отрисовка и движение врагов
        for enemy in enemies:
            enemy.draw()
            enemy.move()
            if enemy.y > screen_height:
                enemies.remove(enemy)
                base_health -= 10

        # Отрисовка башен и их атака
        for tower in towers:
            tower.draw()
            tower.attack(enemies)

        # Отображение информации
        font = pygame.font.SysFont(None, 35)
        health_text = font.render(f"Health: {base_health}", True, BLACK)
        resources_text = font.render(f"Resources: {resources}", True, BLACK)
        screen.blit(health_text, (10, 10))
        screen.blit(resources_text, (10, 50))

        # Проверка на проигрыш
        if base_health <= 0:
            game_over_text = font.render("Game Over!", True, BLACK)
            screen.blit(game_over_text, (screen_width // 2 - 50, screen_height // 2 - 20))
            pygame.display.flip()
            time.sleep(2)  # Пауза, чтобы игрок увидел экран
            pygame.quit()
            quit()

        # Обновление экрана
        pygame.display.flip()

        # Генерация ресурсов
        resources += 1

if __name__ == "__main__":
    main_menu()  # Вход в главное меню
    game_loop()  # Запуск игры