import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;

public class BounceBall{
  static double sqr(double d){return d*d;}
  public static void main(String args[]){
     JFrame frame=new JFrame("BounceBall");
     frame.setSize(600,600);
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     JCanvas canvas=new JCanvas();
     frame.add(canvas);
     frame.setVisible(true);
     
     int    d=100;    // ball diameter
     int    h0=500;   // ground depth from top of canvas
     int    h1=450-d; // height above ground (bottom of ball)
     int    h2=35;    // height below: deformation at bounce
     int    x=200;    // horizontal position of ball
     double t=0;      // time
     double t1=300;   // time above ground
     double t2=340;   // full circle
     while(true){
       t++;if(t>t2)t=0;
       int h=0; //height
       if(t<t1)
         h=(int) (4*h1*(t/t1-sqr(t)/sqr(t1)));
       else
         h=(int) (-4*h2*((t-t1)/(t2-t1)-sqr(t-t1)/sqr(t2-t1)));  
       canvas.startBuffer();
       canvas.clear();
       canvas.setPaint(Color.gray);
       canvas.fillRect(0,h0,x*2+d,20);
       int d1= (int) Math.max(0,-h); //deformation
       canvas.setPaint(Color.red);
       canvas.fillOval(x,h0-h-d,d+d1,d-d1);
       canvas.endBuffer();
       canvas.sleep(10);   
       if(t==50)canvas.writeToImage("bounceballA.jpg",600,600);
       if(t==310)canvas.writeToImage("bounceballB.jpg",600,600);
     }
  }
}
