## Fonctions pour les piles
def estvide(p):
    return(p==[])

def newpile():
    return([])

def depile(p):
    return(p.pop())

def empile(x,p):
    p.append(x)

def sommet(p):
    return(p[-1])


##
Couleurs = ['r', 'k', 'g', 'b', 'y', 'm', 'c']

from pylab import *


Lb = 1600
Hb = 900
cx = 30 #largeur de la croix
cy = 15 #hauteur de la croix

def init_bureau(Lb,Hb):
    xlim(0,Lb)
    ylim(0,Hb)



def croix(fenetre):
    #Fonction pour dessiner la croix selon une fenetre
    x,y,L,H,c = fenetre
    fill([x+L-1-cx,x+L-1-cx,x+L-1,x+L-1],[y+H-1-cy,y+H-1,y+H-1,y+H-1-cy],color = 'r')
    l = min([cx,cy]) - 4
    a,b = x+L-1-cx/2-l/2,y+H+1-cy
    fill([a,a+l-1,a+l,a+1],[b,b+l,b+l,b],color = 'w')
    fill([a,a+1,a+l,a+l-1],[b+l,b+l,b,b],color = 'w')



def dessine(fenetre):
    if fenetre != None:
        init_bureau(Lb,Hb)
        x,y,L,H,c = fenetre
        fill([x,x,x+L,x+L],[y,y+H,y+H,y],color = c)
        croix(fenetre)



def figure(n):
    p = newpile()
    for i in range(n):
        x,y = randint(Lb//100,8*Lb//10),randint(Hb//100,8*Hb//10)
        L,H = randint(Lb//10,Lb-x),randint(Hb//10,Hb-y)
        F = [x,y,L,H]
        c = []
        for i in range(3):
            c.append(random())
        F.append(c)
        empile(F,p)
    return(p)


fig = figure(10)


def affiche(fig):
    if not estvide(fig):
        x = depile(fig)
        affiche(fig)
        dessine(x)
        empile(x,fig)



def est_dans(a,b,fen):
    x,y,L,H,c = fen
    return( a >= x and a<=x+L and b >= y and b <= y + H)



def vider_dans(p1,p2):
    while not estvide(p1):
        empile(depile(p1),p2)

def recherche(x,y,fig):
    aux = newpile()
    while not estvide(fig) and not est_dans(x,y,sommet(fig)):
        empile(depile(fig),aux)
    if not estvide(fig):
        haut = depile(fig)
        a,b,L,H,c = haut
        vider_dans(aux,fig)
        empile(haut,fig)
        if x >= a+L-1-cx and x<=a+L-1 and y >= b+H-1-cy and y <= b + H-1: #Test si (x,y) sur la croix
            depile(fig)
            cla()
    else:
        vider_dans(aux,fig)
    affiche(fig)


affiche(fig)


def evolue(event):
    x,y = event.xdata,event.ydata
    print(x,y)
    if event.button == 1:
       recherche(x,y,fig)
    draw()

cid = connect('button_press_event',evolue)
show()