# -------------------------------------------------
# LEÇON 13 — BOSS FIGHT
#
# Objectif :
# créer un vrai combat de boss
#
# Le joueur :
# - se déplace
# - tire des projectiles
# - possède des points de vie
#
# Le boss :
# - se déplace automatiquement
# - tire vers le joueur
# - possède beaucoup de vie
#
# Concepts importants :
# - systèmes combinés
# - boss
# - projectiles ennemis
# - barre de vie
# - états du jeu
# - victoire / défaite
#
# IMPORTANT :
# Ce projet réutilise presque TOUT
# ce qu'on a appris pendant le cours.
# -------------------------------------------------


import pygame
import random

# -------------------------------------------------
# INITIALISATION
# -------------------------------------------------

pygame.init()


# -------------------------------------------------
# FENÊTRE
# -------------------------------------------------

WIDTH = 800
HEIGHT = 600

screen = pygame.display.set_mode((WIDTH, HEIGHT))

pygame.display.set_caption(
    "Leçon 13 - Boss Fight"
)


# -------------------------------------------------
# TEMPS / FPS
# -------------------------------------------------

clock = pygame.time.Clock()

FPS = 60


# -------------------------------------------------
# COULEURS
# -------------------------------------------------

BG_COLOR = (20, 20, 30)

PLAYER_COLOR = (100, 220, 120)

BOSS_COLOR = (220, 80, 80)

BULLET_COLOR = (255, 255, 100)

BOSS_BULLET_COLOR = (255, 120, 120)

TEXT_COLOR = (240, 240, 240)

HP_BAR_COLOR = (80, 220, 120)

HP_BAR_BG = (70, 70, 70)

BOSS_HP_COLOR = (220, 80, 80)


# -------------------------------------------------
# POLICES
# -------------------------------------------------

font = pygame.font.Font(None, 36)

big_font = pygame.font.Font(None, 72)


# -------------------------------------------------
# JOUEUR
# -------------------------------------------------

# Taille du joueur
player_size = 50

# Position du joueur
player_x = WIDTH // 2
player_y = HEIGHT - 80

# Vitesse du joueur
player_speed = 6


# -------------------------------------------------
# VIE DU JOUEUR
# -------------------------------------------------

player_max_health = 100

player_health = player_max_health


# -------------------------------------------------
# COOLDOWN DE DÉGÂTS
# -------------------------------------------------
# Empêche le joueur de perdre
# toute sa vie instantanément.

player_damage_cooldown = 0

PLAYER_DAMAGE_DELAY = 60


# -------------------------------------------------
# BALLES DU JOUEUR
# -------------------------------------------------

player_bullets = []

# Taille des projectiles
bullet_width = 8
bullet_height = 18

# Vitesse des projectiles
bullet_speed = 8


# -------------------------------------------------
# COOLDOWN DE TIR
# -------------------------------------------------
# Empêche le spam de tirs.

shoot_cooldown = 0

SHOOT_DELAY = 15


# -------------------------------------------------
# BOSS
# -------------------------------------------------

# Taille du boss
boss_size = 120

# Position du boss
boss_x = WIDTH // 2 - boss_size // 2
boss_y = 60

# Mouvement horizontal du boss
boss_speed = 4

# Direction :
# 1 = droite
# -1 = gauche
boss_direction = 1


# -------------------------------------------------
# VIE DU BOSS
# -------------------------------------------------

boss_max_health = 300

boss_health = boss_max_health


# -------------------------------------------------
# BALLES DU BOSS
# -------------------------------------------------

boss_bullets = []

# Taille des projectiles ennemis
boss_bullet_size = 14

# Vitesse des projectiles ennemis
boss_bullet_speed = 5


# -------------------------------------------------
# TIMER DE TIR DU BOSS
# -------------------------------------------------
# Le boss tire automatiquement
# toutes les X frames.

boss_shoot_timer = 0

BOSS_SHOOT_DELAY = 50


# -------------------------------------------------
# EXPLOSIONS
# -------------------------------------------------
# Effets visuels quand une balle touche.

explosions = []


# -------------------------------------------------
# SCORE
# -------------------------------------------------

score = 0


# -------------------------------------------------
# ÉTATS DU JEU
# -------------------------------------------------

game_over = False

victory = False


# -------------------------------------------------
# BOUCLE PRINCIPALE
# -------------------------------------------------

running = True

while running:


    # ---------------------------------------------
    # ÉVÉNEMENTS
    # ---------------------------------------------

    for event in pygame.event.get():


        # -----------------------------------------
        # FERMER FENÊTRE
        # -----------------------------------------

        if event.type == pygame.QUIT:

            running = False


        # -----------------------------------------
        # CLAVIER
        # -----------------------------------------

        if event.type == pygame.KEYDOWN:


            # -------------------------------------
            # TIR DU JOUEUR
            # -------------------------------------

            if (
                event.key == pygame.K_SPACE
                and shoot_cooldown == 0
                and not game_over
                and not victory
            ):

                # Création d'une balle
                bullet = {

                    # Position horizontale :
                    # centre du joueur
                    "x": (
                        player_x
                        + player_size // 2
                        - bullet_width // 2
                    ),

                    # Position verticale :
                    # haut du joueur
                    "y": player_y

                }

                # Ajouter balle dans liste
                player_bullets.append(bullet)

                # Relancer cooldown
                shoot_cooldown = SHOOT_DELAY


            # -------------------------------------
            # RESTART
            # -------------------------------------

            if (
                event.key == pygame.K_r
                and (game_over or victory)
            ):


                # Réinitialiser vie joueur
                player_health = player_max_health


                # Réinitialiser vie boss
                boss_health = boss_max_health


                # Réinitialiser position joueur
                player_x = WIDTH // 2


                # Réinitialiser position boss
                boss_x = WIDTH // 2 - boss_size // 2


                # Vider listes
                player_bullets.clear()

                boss_bullets.clear()

                explosions.clear()


                # Réinitialiser score
                score = 0


                # Réinitialiser états
                game_over = False

                victory = False


    # ---------------------------------------------
    # COOLDOWNS
    # ---------------------------------------------

    if shoot_cooldown > 0:

        shoot_cooldown -= 1


    if player_damage_cooldown > 0:

        player_damage_cooldown -= 1


    # ---------------------------------------------
    # CLAVIER
    # ---------------------------------------------

    keys = pygame.key.get_pressed()


    # Empêcher mouvement après fin
    if not game_over and not victory:


        # Gauche
        if keys[pygame.K_LEFT]:

            player_x -= player_speed


        # Droite
        if keys[pygame.K_RIGHT]:

            player_x += player_speed


    # ---------------------------------------------
    # LIMITES ÉCRAN
    # ---------------------------------------------

    player_x = max(
        0,
        min(WIDTH - player_size, player_x)
    )


    # ---------------------------------------------
    # MOUVEMENT DU BOSS
    # ---------------------------------------------

    if not game_over and not victory:


        # Déplacement horizontal
        boss_x += boss_speed * boss_direction


        # Rebonds sur les côtés
        if boss_x <= 0:

            boss_direction = 1


        if boss_x >= WIDTH - boss_size:

            boss_direction = -1


    # ---------------------------------------------
    # TIR AUTOMATIQUE DU BOSS
    # ---------------------------------------------

    boss_shoot_timer += 1


    # Le boss tire toutes les X frames
    if (
        boss_shoot_timer >= BOSS_SHOOT_DELAY
        and not game_over
        and not victory
    ):


        # Réinitialiser timer
        boss_shoot_timer = 0


        # Créer projectile ennemi
        boss_bullet = {

            # Centre horizontal du boss
            "x": boss_x + boss_size // 2,

            # Bas du boss
            "y": boss_y + boss_size

        }


        # Ajouter projectile
        boss_bullets.append(boss_bullet)


    # ---------------------------------------------
    # MOUVEMENT DES BALLES JOUEUR
    # ---------------------------------------------

    for bullet in player_bullets:


        # Les balles montent
        bullet["y"] -= bullet_speed


    # ---------------------------------------------
    # SUPPRESSION BALLES HORS ÉCRAN
    # ---------------------------------------------

    player_bullets = [

        bullet

        for bullet in player_bullets

        if bullet["y"] > -bullet_height

    ]


    # ---------------------------------------------
    # MOUVEMENT DES BALLES DU BOSS
    # ---------------------------------------------

    for bullet in boss_bullets:


        # Les balles ennemies descendent
        bullet["y"] += boss_bullet_speed


    # ---------------------------------------------
    # SUPPRESSION BALLES ENNEMIES
    # ---------------------------------------------

    boss_bullets = [

        bullet

        for bullet in boss_bullets

        if bullet["y"] < HEIGHT

    ]


    # ---------------------------------------------
    # COLLISION :
    # BALLES JOUEUR / BOSS
    # ---------------------------------------------

    # Rectangle invisible du boss
    boss_rect = pygame.Rect(

        boss_x,
        boss_y,

        boss_size,
        boss_size
    )


    for bullet in player_bullets[:]:


        # Rectangle invisible de balle
        bullet_rect = pygame.Rect(

            bullet["x"],
            bullet["y"],

            bullet_width,
            bullet_height
        )


        # Collision détectée
        if bullet_rect.colliderect(boss_rect):


            # Supprimer balle
            if bullet in player_bullets:

                player_bullets.remove(bullet)


            # Dégâts boss
            boss_health -= 10


            # Ajouter explosion
            explosions.append({

                "x": bullet["x"],

                "y": bullet["y"],

                "radius": 5

            })


            # Ajouter score
            score += 1


    # ---------------------------------------------
    # COLLISION :
    # BALLES BOSS / JOUEUR
    # ---------------------------------------------

    # Rectangle invisible du joueur
    player_rect = pygame.Rect(

        player_x,
        player_y,

        player_size,
        player_size
    )


    for bullet in boss_bullets[:]:


        bullet_rect = pygame.Rect(

            bullet["x"],
            bullet["y"],

            boss_bullet_size,
            boss_bullet_size
        )


        # Collision détectée
        if bullet_rect.colliderect(player_rect):


            # Vérifier cooldown
            if player_damage_cooldown == 0:


                # Perdre vie
                player_health -= 10


                # Relancer cooldown
                player_damage_cooldown = PLAYER_DAMAGE_DELAY


                # Supprimer projectile
                if bullet in boss_bullets:

                    boss_bullets.remove(bullet)


    # ---------------------------------------------
    # MISE À JOUR EXPLOSIONS
    # ---------------------------------------------

    for explosion in explosions:


        # Agrandir explosion
        explosion["radius"] += 2


    # Garder petites explosions seulement
    explosions = [

        explosion

        for explosion in explosions

        if explosion["radius"] < 30

    ]


    # ---------------------------------------------
    # CONDITIONS DE FIN
    # ---------------------------------------------

    if player_health <= 0:

        game_over = True


    if boss_health <= 0:

        victory = True


    # ---------------------------------------------
    # DESSIN
    # ---------------------------------------------

    screen.fill(BG_COLOR)


    # ---------------------------------------------
    # JOUEUR
    # ---------------------------------------------

    pygame.draw.rect(

        screen,

        PLAYER_COLOR,

        (
            player_x,
            player_y,

            player_size,
            player_size
        )
    )


    # ---------------------------------------------
    # BOSS
    # ---------------------------------------------

    pygame.draw.rect(

        screen,

        BOSS_COLOR,

        (
            boss_x,
            boss_y,

            boss_size,
            boss_size
        )
    )


    # ---------------------------------------------
    # BALLES JOUEUR
    # ---------------------------------------------

    for bullet in player_bullets:


        pygame.draw.rect(

            screen,

            BULLET_COLOR,

            (
                bullet["x"],
                bullet["y"],

                bullet_width,
                bullet_height
            )
        )


    # ---------------------------------------------
    # BALLES BOSS
    # ---------------------------------------------

    for bullet in boss_bullets:


        pygame.draw.circle(

            screen,

            BOSS_BULLET_COLOR,

            (
                bullet["x"],
                bullet["y"]
            ),

            boss_bullet_size // 2
        )


    # ---------------------------------------------
    # EXPLOSIONS
    # ---------------------------------------------

    for explosion in explosions:


        pygame.draw.circle(

            screen,

            (255, 200, 50),

            (
                explosion["x"],
                explosion["y"]
            ),

            explosion["radius"]
        )


    # ---------------------------------------------
    # BARRE DE VIE JOUEUR
    # ---------------------------------------------

    player_bar_width = 200

    player_current_width = (

        player_health / player_max_health

    ) * player_bar_width


    # Fond gris
    pygame.draw.rect(

        screen,

        HP_BAR_BG,

        (
            20,
            20,

            player_bar_width,
            20
        )
    )


    # Vie actuelle
    pygame.draw.rect(

        screen,

        HP_BAR_COLOR,

        (
            20,
            20,

            player_current_width,
            20
        )
    )


    # ---------------------------------------------
    # BARRE DE VIE BOSS
    # ---------------------------------------------

    boss_bar_width = 300

    boss_current_width = (

        boss_health / boss_max_health

    ) * boss_bar_width


    # Fond gris
    pygame.draw.rect(

        screen,

        HP_BAR_BG,

        (
            250,
            20,

            boss_bar_width,
            20
        )
    )


    # Vie actuelle boss
    pygame.draw.rect(

        screen,

        BOSS_HP_COLOR,

        (
            250,
            20,

            boss_current_width,
            20
        )
    )


    # ---------------------------------------------
    # SCORE
    # ---------------------------------------------

    score_text = font.render(

        f"Score: {score}",

        True,

        TEXT_COLOR
    )

    screen.blit(score_text, (20, 50))


    # ---------------------------------------------
    # GAME OVER
    # ---------------------------------------------

    if game_over:


        game_over_text = big_font.render(

            "GAME OVER",

            True,

            TEXT_COLOR
        )


        restart_text = font.render(

            "Appuie sur R pour rejouer",

            True,

            TEXT_COLOR
        )


        screen.blit(
            game_over_text,
            (220, 250)
        )

        screen.blit(
            restart_text,
            (250, 330)
        )


    # ---------------------------------------------
    # VICTOIRE
    # ---------------------------------------------

    if victory:


        victory_text = big_font.render(

            "VICTOIRE !",

            True,

            TEXT_COLOR
        )


        restart_text = font.render(

            "Appuie sur R pour rejouer",

            True,

            TEXT_COLOR
        )


        screen.blit(
            victory_text,
            (250, 250)
        )

        screen.blit(
            restart_text,
            (250, 330)
        )


    # ---------------------------------------------
    # UPDATE ÉCRAN
    # ---------------------------------------------

    pygame.display.update()

    clock.tick(FPS)


# -------------------------------------------------
# FIN DU JEU
# -------------------------------------------------

pygame.quit()