from tkinter import *
from math import *
from random import randint


def move():
    global xc,yc,dx,dy,r,flag,delai
    if (xc+r+dx > 500) or (xc-r+dx<0) :
        dx = -dx
    if (yc+r+dy > 500) or (yc-r+dy<0):
        dy = -dy
    ecran.move(rond,dx,dy)
    xc = xc + dx
    yc = yc + dy
    if flag :
        fenetre.after(delai,move)    

def stop_anim():
    global flag
    flag = False

def start_anim():
    global flag
    ecran.itemconfigure(rond,fill='blue')
    if not flag :
        flag = True
        move()

def reaction(event):
    global nbclick,flag,dx,dy,r,delai,xc,yc
    x,y=event.x,event.y
    nbclick += 1
    l2.configure(text=str(nbclick))
    if sqrt((x-xc)**2+(y-yc)**2) <= r :
        flag = False
        ecran.itemconfigure(rond,fill='red')
        a = randint(-15,15)
        b = randint(-15,15)
        dx = a*10/sqrt(a**2+b**2)
        dy = b*10/sqrt(a**2+b**2)
        r-=1
        ecran.coords(rond,xc-r,yc-r,xc+r,yc+r)
        delai -= 3
        fenetre.after(1000,start_anim)

    
fenetre=Tk()
fenetre.title("Jeu du clic")

ecran = Canvas(fenetre,width=500,height=500,bg="dark grey")
ecran.pack(side=LEFT,padx=5,pady=5)

xc,yc=250,250
r = 25
delai = 50
dx,dy=15*10/sqrt(325),10*10/325
flag = False
nbclick = 0

rond = ecran.create_oval(xc-r,yc-r,xc+r,yc+r,fill='blue')

b1 = Button(fenetre,text="Quitter",width=8,command=fenetre.destroy)
b1.pack(side = BOTTOM)

b2 = Button(fenetre,text="Démarrer",width=8,command=start_anim)
b2.pack()

b3 = Button(fenetre,text="Pause",width=8,command=stop_anim)
b3.pack()
f1 = Frame(fenetre)
l1 = Label(f1,text="Nombre de clics effectués :")
l1.pack(side=LEFT)
l2 = Label(f1,text="0")
l2.pack(side=RIGHT)
f1.pack(padx=5,pady=5)


ecran.bind("<Button-1>",reaction)

fenetre.mainloop()





##def reaction (event) :
##    global xc,yc,rond,couleur
##    x,y=event.x,event.y
##    print(x,y)
##    if sqrt((x-xc)**2+(y-yc)**2) > 20:
##        ecran.itemconfigure(rond,fill=couleur.get())
##        ecran.move(rond,x-xc,y-yc)
##        xc,yc=x,y
##    else :
##        ecran.itemconfigure(rond,fill='red')
##        
##def bouger(event) :
##    global xc,yc,rond,couleur
##    x,y=event.x,event.y
##    ecran.move(rond,x-xc,y-yc)
##    xc,yc=x,y
##
##
##def change_couleur():
##    global couleur,rond
##    ecran.itemconfigure(rond,fill=couleur.get())
