#!/usr/bin/env python3
from tkinter import Tk,Canvas,ALL
# .......................................... open Tkinter root window
root=Tk()
root.title("Gravity ball")
# ........................................... canvas width and height
cw=800
ch=400
# ......................................... add canvas to root window
canvas=Canvas(root,width=cw,height=ch,background='white')
canvas.grid(row=0,column=1)
# ......................................................... variables
delay=20 #milliseconds
rad=20
color="red"
x=rad
y=ch-rad
vx=4.0
vy=-8.0
ay=0.1
# ......................................................... main loop
while True:
  # ............................................. draw ball on canvas
  canvas.delete(ALL)
  canvas.create_oval(x-rad,y-rad,x+rad,y+rad,fill=color)
  canvas.update()
  # ......................... update position and velocity components
  Ay=ay-vy*0.003
  vx=0.997*vx
  x+=vx
  y+=vy+0.5*Ay
  vy+=Ay
  # ..................... is the ball bouncing on the canvas borders?
  if (x+rad)>=cw:
    vx=-abs(vx)
    #x=2*(cw-rad)-x
  elif x<=rad:
    vx=abs(vx)
    #x=2*rad-x
  if (y+rad)>=ch:
    vy=-abs(vy)
    #y=2*(ch-rad)-y
  elif y<=rad:
    vy=abs(vy)
    #y=2*rad-y
  # ................................................. wait delay time
  canvas.after(delay)
  
