import random
import pygame
import os

game_folder = os.path.dirname(__file__)
img_folder = os.path.join(game_folder, 'img')
icon_path = os.path.join(img_folder, 'icon.png')

WIDTH = 800
HEIGHT = 720
FPS = 30

WHITE = (255, 255, 255)  # Белый цвет
BLACK = (0, 0, 0)  # Чёрный
RED = (255, 0, 0)  # Красный
GREEN = (0, 255, 0)  # Зелёный
BLUE = (0, 0, 255)  # Синий
VIOLET = (238, 130, 238)  # Фиолетовый
YELLOW = (255, 255, 0)  # Жёлтый

# Доступные фоны
background_images = {
    'фон1': pygame.image.load(os.path.join(img_folder, 'fon1.png')),
    'фон2': pygame.image.load(os.path.join(img_folder, 'fon2.png')),
}
current_background = None  # Текущий фон

# Группы спрайтов
all_sprites = pygame.sprite.Group()
mobs = pygame.sprite.Group()
bullets = pygame.sprite.Group()

class Player(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load(os.path.join(img_folder, 'player.png')).convert_alpha()
        self.rect = self.image.get_rect()
        self.rect.centerx = WIDTH // 2
        self.rect.bottom = HEIGHT - 10
        self.speedx = 0

    def update(self):
        self.speedx = 0
        keystate = pygame.key.get_pressed()
        if keystate[pygame.K_a]:
            self.speedx = -16
        if keystate[pygame.K_d]:
            self.speedx = 16
        self.rect.x += self.speedx

        if self.rect.right > WIDTH:
            self.rect.right = WIDTH
        if self.rect.left < 0:
            self.rect.left = 0

    def shoot(self):
        bullet = Bullet(self.rect.centerx, self.rect.top)
        all_sprites.add(bullet)
        bullets.add(bullet)


class Mob(pygame.sprite.Sprite):
    def __init__(self, type=1):
        pygame.sprite.Sprite.__init__(self)
        image_file = 'mob.png' if type % 2 == 1 else 'mob(2).png'
        self.image = pygame.image.load(os.path.join(img_folder, image_file)).convert_alpha()
        self.rect = self.image.get_rect()
        self.rect.x = random.randrange(WIDTH - self.rect.width)
        self.rect.y = random.randrange(-100, -40)
        self.speedy = random.randrange(8, 16)
        self.speedx = random.randrange(-3, 3)

    def update(self):
        self.rect.x += self.speedx
        self.rect.y += self.speedy
        if self.rect.top > HEIGHT + 10 or self.rect.left < -25 or self.rect.right > WIDTH + 20:
            self.rect.x = random.randrange(WIDTH - self.rect.width)
            self.rect.y = random.randrange(-100, -40)
            self.speedy = random.randrange(1, 8)


class Bullet(pygame.sprite.Sprite):
    def __init__(self, x, y):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load(os.path.join(img_folder, 'bullet.png')).convert_alpha()
        self.rect = self.image.get_rect()
        self.rect.bottom = y
        self.rect.centerx = x
        self.speedy = -50

    def update(self):
        self.rect.y += self.speedy
        if self.rect.bottom < 0:
            self.kill()


# Экран начала игры
def show_start_screen():
    screen.fill(WHITE)
    draw_text(screen, "UFO KILLER", 64, WIDTH // 2, HEIGHT // 4)

    # Кнопки для смены фона
    button_width = 100
    button_height = 50
    margin = 20
    x_position = WIDTH // 2 - button_width * 1.5 - margin
    y_position = HEIGHT // 2

    # Кнопка для фона 1
    button_fon1 = pygame.Rect(x_position, y_position, button_width, button_height)
    pygame.draw.rect(screen, BLACK, button_fon1)
    draw_text(screen, "Фон 1", 20, button_fon1.centerx, button_fon1.centery, color=WHITE)

    # Кнопка для фона 2
    button_fon2 = pygame.Rect(x_position + button_width + margin, y_position, button_width, button_height)
    pygame.draw.rect(screen, BLACK, button_fon2)
    draw_text(screen, "Фон 2", 20, button_fon2.centerx, button_fon2.centery, color=WHITE)

    # Кнопка для белого фона
    button_white = pygame.Rect(x_position + 2 * (button_width + margin), y_position, button_width, button_height)
    pygame.draw.rect(screen, BLACK, button_white)
    draw_text(screen, "Белый фон", 20, button_white.centerx, button_white.centery, color=WHITE)

    # Изображение кнопки PLAY
    play_button_image = pygame.image.load(os.path.join(img_folder, 'play.png'))
    play_button_rect = play_button_image.get_rect(center=(WIDTH // 2, HEIGHT * 3 / 4))
    screen.blit(play_button_image, play_button_rect)

    pygame.display.flip()

    # Ждём либо нажатия клавиши, либо клика на одну из кнопок
    waiting = True
    while waiting:
        clock.tick(FPS)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()

            # Нажатие на кнопку Play
            if event.type == pygame.MOUSEBUTTONDOWN:
                pos = pygame.mouse.get_pos()
                if play_button_rect.collidepoint(pos):
                    waiting = False
                elif button_fon1.collidepoint(pos):
                    set_current_background('фон1')
                elif button_fon2.collidepoint(pos):
                    set_current_background('фон2')
                elif button_white.collidepoint(pos):
                    set_current_background(None)


# Экран завершения игры
def show_game_over_screen(score):
    screen.fill(WHITE)
    draw_text(screen, f"ВЫ ПРОИГРАЛИ! Ваш счёт: {score}", 64, WIDTH // 2, HEIGHT // 4)
    draw_text(screen, "Нажмите RESTART, чтобы вернуться в главное меню", 22, WIDTH // 2, HEIGHT * 3 / 4)

    # Изображение кнопки RESTART
    restart_button_image = pygame.image.load(os.path.join(img_folder, 'restart.png'))
    restart_button_rect = restart_button_image.get_rect(center=(WIDTH // 2, HEIGHT * 3 / 4 + 100))
    screen.blit(restart_button_image, restart_button_rect)

    pygame.display.flip()

    # Ждём клика на кнопку RESTART
    waiting = True
    while waiting:
        clock.tick(FPS)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
            if event.type == pygame.MOUSEBUTTONDOWN:
                pos = pygame.mouse.get_pos()
                if restart_button_rect.collidepoint(pos):
                    waiting = False
                    show_start_screen()  # Возврат в главное меню


# Ждём ввода Enter для перезапуска игры
def wait_for_enter():
    waiting = True
    while waiting:
        clock.tick(FPS)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
            if event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN:
                waiting = False


# Установщик текущего фона
def set_current_background(bg_name):
    global current_background
    current_background = bg_name


# Функция для вывода текста на экран
def draw_text(surf, text, size, x, y, color=BLACK):
    font = pygame.font.Font(font_name, size)
    text_surface = font.render(text, True, color)
    text_rect = text_surface.get_rect()
    text_rect.midtop = (x, y)
    surf.blit(text_surface, text_rect)


# Главная переменная для счёта
score = 0

pygame.init()
pygame.mixer.init()

screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("UFO Killer")
pygame.display.set_icon(pygame.image.load(icon_path))

clock = pygame.time.Clock()
font_name = pygame.font.match_font('arial')


def main():
    global score, current_background
    show_start_screen()  # Начинаем с главного экрана

    # Очистка игровых объектов
    score = 0
    all_sprites.empty()
    mobs.empty()
    bullets.empty()

    player = Player()
    all_sprites.add(player)

    type_counter = 1
    for _ in range(8):
        m = Mob(type_counter)
        all_sprites.add(m)
        mobs.add(m)
        type_counter += 1

    running = True
    while running:
        clock.tick(FPS)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
                player.shoot()

        all_sprites.update()

        # Столкновения мобов и пуль
        hits = pygame.sprite.groupcollide(mobs, bullets, True, True)
        for hit in hits:
            score += 1
            new_mob_type = len(all_sprites.sprites()) % 2 + 1
            new_mob = Mob(new_mob_type)
            all_sprites.add(new_mob)
            mobs.add(new_mob)

        # Столкновение игрока с мобами
        hits = pygame.sprite.spritecollide(player, mobs, False)
        if hits:
            running = False

        # Рисуем фон
        if current_background is not None:
            screen.blit(background_images[current_background], (0, 0))
        else:
            screen.fill(WHITE)

        # Отрисовываем игровой интерфейс
        all_sprites.draw(screen)
        draw_text(screen, f'Вы убили: {score}', 30, WIDTH // 2, 10)

        pygame.display.flip()

    if not running:
        show_game_over_screen(score)  # Переход на экран окончания игры


if __name__ == "__main__":
    main()