from tkinter import *
from random import *

nbrenv=0
ddpl=500
nbcrp=10 # nombre de crèpe
lf=800
hf=500
dd=50
lcp=[]
lcpep=[]
lr=[]

fen = Tk()

cadre = Frame(fen, width =lf, height =hf, bg="light yellow")
cadre.pack()

c=Canvas(cadre, height=hf, width=lf, bg="white")
c.place(x=0, y=0)

def deleterect():
    for rect in lr:
        c.delete(rect)

def deplacement1():
    global nbrenv,ddpl
    deleterect ()
    for i in range (len(lcpep)):
        lr.append(c.create_rectangle(((lf-lcpep[i])//2,hf-20-20*i,(lf+lcpep[i])//2,hf-20-20*(i+1)), outline="blue", fill="green", width=2))
    for i in range (len(lcp)):
        lr.append(c.create_rectangle(((lf-lcp[i])//2,hf-20-20*(i+len(lcpep)),(lf+lcp[i])//2,hf-20-20*(i+len(lcpep)+1)), outline="blue", fill="red", width=2))
    #print ("len(lcpep)=",len(lcpep))
    nbrenv=nbrenv+1
    lcp.reverse()
    lcpep.append(lcp[0])
    del lcp[0]
    fen.after(ddpl,deplacement)


def deplacement():
    global nbrenv,ddpl
    deleterect ()
    for i in range (len(lcpep)):
        lr.append(c.create_rectangle(((lf-lcpep[i])//2,hf-20-20*i,(lf+lcpep[i])//2,hf-20-20*(i+1)), outline="blue", fill="green", width=2))
    for i in range (len(lcp)):
        lr.append(c.create_rectangle(((lf-lcp[i])//2,hf-20-20*(i+len(lcpep)),(lf+lcp[i])//2,hf-20-20*(i+len(lcpep)+1)), outline="blue", fill="red", width=2))
    if len(lcp)!=0:
        pmax=lcp.index(max(lcp))
        #print ("pmax=",pmax)
        if pmax!=0:
            nbrenv=nbrenv+1
            a=lcp[pmax:]
            a.reverse()
            for i in range(pmax,len(lcp)):
                lcp[i]=a[i-pmax]
            fen.after(ddpl,deplacement1)
        else:
            lcpep.append(lcp[0])
            del lcp[0]
            fen.after(ddpl,deplacement)
    else:
        textper="nombre de renversement "+str(nbrenv)+" pour "+str(nbcrp)+" crêpes."
        lbtext= Label( fen, text=textper, relief=RAISED )
        lbtext.pack()
        print ("fin")
        print ("nombre de renversement",nbrenv,"pour",nbcrp,"crêpes")

for i in range(nbcrp):
    lcp.append(50+50*i)
shuffle(lcp)

deplacement()

fen.mainloop()