import matplotlib.pyplot as pl

def hanoi_graph(n):
    """Tour de Hanoi avec rendu graphique"""
    global compt
    L=[[k for k in range(n,0,-1)],[],[]] 
    # contient les listes représentant les piquets 1, 2, 3.
    compt=0 # compteur de coups
    h=1/n
    pl.axis([0,1,0,1])
    C=['b', 'g', 'r', 'c', 'm', 'y', 'k']
    
    def rectangle(i,d,k):
        pl.plot([(k+1)/4-0.5*(0.25-(n-d)/(5*n)),(k+1)/4+0.5*(0.25-(n-d)/(5*n)),(k+1)/4+0.5*(0.25-(n-d)/(5*n)),(k+1)/4-0.5*(0.25-(n-d)/(5*n)),(k+1)/4-0.5*(0.25-(n-d)/(5*n))],[h*i,h*i,h*(i+1),h*(i+1),h*i],C[d%len(C)],linewidth=3)
    
    
    def piquet(k,L):
        for i in range(len(L)):
            rectangle(i,L[i],k)    
    
    def afficher():
        """Affichage en fonction du contenu des listes dans L"""
#         print('*****')
#         for k in (0,1,2):
#             ligne="*["+str(k+1)+"]: "
#             for j in L[k]:
#                 ligne+=str(j)
#             print(ligne)
#         print('*****\n')
        
        for k in (0,1,2):
            piquet(k,L[k])
        
        pl.axis([0,1,0,1])
        pl.show()
        pl.pause(.001)
        pl.clf()
        
        

    def hanoi(nb,pos_init,pos_fin):
        """Tour de Hanoi récursif avec affichage"""
        global compt
        if nb==1:  
            # On déplace effectivement la pièce
            L[pos_fin-1].append(L[pos_init-1].pop())
            # On l'affiche
            print(compt,": Déplacer de",pos_init,"vers",pos_fin)
            afficher()
            # On incrémente le compteur
            compt+=1                          
        else:
            # Position intermédiaire
            pos_inter=6-pos_init-pos_fin    
            # Premier appel récursif
            hanoi(nb-1,pos_init,pos_inter)
            #passage du n ieme disque
            hanoi(1, pos_init, pos_fin)
            # Deuxième appel récursif
            hanoi(nb-1,pos_inter,pos_fin)
            
    #on appelle la fonction Hanoi à l'intérieur de la fonction hanoi_graph        
    hanoi(n,1,3)
    print("C'est gagné en",compt,"coups !")
hanoi_graph(10)
