#Bibliothèque
import os
import random
import time

#Fonctions
def creer_grille(taille):
    return [["." for _ in range(taille)] for _ in range(taille)]

def affiche_jeu(grille_joueur, tirs_joueur):
    os.system("cls" if os.name == "nt" else "clear")
    print("      VOS NAVIRES                    VOS TIRS")
    print("  0 1 2 3 4 5 6 7            0 1 2 3 4 5 6 7")
    for i in range(8):
        joueur = " ".join(grille_joueur[i])
        tirs = " ".join(tirs_joueur[i])
        print(f"{i} {joueur}          {i} {tirs}")

def est_valide(grille, l, c, taille, direction):
    # Vérifie si le navire peut être placé ici
    for i in range(taille):
        nl = l + (i if direction == "V" else 0)
        nc = c + (i if direction == "H" else 0)
        if nl < 0 or nl >= 8 or nc < 0 or nc >= 8 or grille[nl][nc] != ".":
            return False
    return True

def placer_navires_ia(grille, navires):
    for n_taille in navires:
        place = False
        while not place:
            l, c, d = random.randint(0, 7), random.randint(0, 7), random.choice(["H", "V"])
            if est_valide(grille, l, c, n_taille, d):
                for i in range(n_taille):
                    grille[l + (i if d == "V" else 0)][c + (i if d == "H" else 0)] = "S"
                place = True

def calculer_probabilites(grille_tirs, navires_restants):
    # C'est ici que l'IA devient "intelligente"
    # Elle crée une carte de score pour chaque case
    scores = [[0 for _ in range(8)] for _ in range(8)]
    
    for n_taille in navires_restants:
        for l in range(8):
            for c in range(8):
                for d in ["H", "V"]:
                    if est_valide(grille_tirs, l, c, n_taille, d):
                        # On vérifie qu'il n'y a pas déjà de "Raté" (O) sur le chemin
                        for i in range(n_taille):
                            nl, nc = l + (i if d == "V" else 0), c + (i if d == "H" else 0)
                            # Si on a un "Touché" (X) à côté, on augmente énormément le score
                            scores[nl][nc] += 1
                            if grille_tirs[nl][nc] == "X":
                                scores[nl][nc] += 50 

    # On remet à 0 les cases déjà tirées
    for l in range(8):
        for c in range(8):
            if grille_tirs[l][c] != ".":
                scores[l][c] = -1
    return scores

def ia_coup_intelligent(grille_tirs, navires_ennemis):
    scores = calculer_probabilites(grille_tirs, navires_ennemis)
    max_score = -2
    meilleurs_coups = []
    
    for l in range(8):
        for c in range(8):
            if scores[l][c] > max_score:
                max_score = scores[l][c]
                meilleurs_coups = [(l, c)]
            elif scores[l][c] == max_score:
                meilleurs_coups.append((l, c))
    
    return random.choice(meilleurs_coups)

def verifier_victoire(grille):
    for ligne in grille:
        if "S" in ligne: return False
    return True

#initialisation
taille_grille = 8
navires_a_placer = [3, 2, 2] # Un croiseur et deux torpilleurs
grille_joueur = creer_grille(taille_grille)
tirs_joueur = creer_grille(taille_grille)
grille_ia = creer_grille(taille_grille)
tirs_ia = creer_grille(taille_grille)

# Placement des navires par le joueur
placer_navires_ia(grille_ia, navires_a_placer)
for n in navires_a_placer:
    affiche_jeu(grille_joueur, tirs_joueur)
    place = False
    while not place:
        try:
            print(f"\nPlacez votre navire de taille {n}")
            l = int(input("Ligne (0-7): "))
            c = int(input("Colonne (0-7): "))
            d = input("Direction (H/V): ").upper()
            if est_valide(grille_joueur, l, c, n, d):
                for i in range(n):
                    grille_joueur[l + (i if d == "V" else 0)][c + (i if d == "H" else 0)] = "S"
                place = True
            else: print("Emplacement impossible !")
        except: print("Entrée invalide.")

#Programme principal
fin = False
while not fin:
    affiche_jeu(grille_joueur, tirs_joueur)
    
    # --- TOUR DU JOUEUR ---
    valide = False
    while not valide:
        try:
            print("\nÀ VOUS DE TIRER")
            l = int(input("Ligne: "))
            c = int(input("Colonne: "))
            if 0 <= l < 8 and 0 <= c < 8 and tirs_joueur[l][c] == ".":
                valide = True
                if grille_ia[l][c] == "S":
                    print("TOUCHÉ !")
                    tirs_joueur[l][c] = "X"
                    grille_ia[l][c] = "X"
                else:
                    print("MANQUÉ.")
                    tirs_joueur[l][c] = "O"
            else: print("Tir déjà effectué ou hors zone.")
        except: print("Entrée invalide.")

    if verifier_victoire(grille_ia):
        affiche_jeu(grille_joueur, tirs_joueur)
        print("\nVICTOIRE ! Vous avez coulé la flotte ennemie.")
        fin = True
        break

    # --- TOUR DE L'IA ---
    print("\nL'IA réfléchit...")
    time.sleep(1)
    l_ia, c_ia = ia_coup_intelligent(tirs_ia, navires_a_placer)
    
    if grille_joueur[l_ia][c_ia] == "S":
        print(f"L'IA tire en ({l_ia},{c_ia}) : TOUCHÉ !")
        grille_joueur[l_ia][c_ia] = "X"
        tirs_ia[l_ia][c_ia] = "X"
    else:
        print(f"L'IA tire en ({l_ia},{c_ia}) : MANQUÉ.")
        tirs_ia[l_ia][c_ia] = "O"
    time.sleep(1)

    if verifier_victoire(grille_joueur):
        affiche_jeu(grille_joueur, tirs_joueur)
        print("\nDÉFAITE... L'IA a gagné.")
        fin = True
