import java.awt.*;
public class BouncingBallCanvasa extends Canvas {
  int x,y,x1,y1,dx=-2,dy=-4,dx1=-4,dy1=-4,radius=20,length=40,breadth=25; 
  Dimension d;
  Image im;
  Graphics offscreen;
  Color backgroundcolor = Color.black;
  Color rectanglecolor = Color.green;
  Color ballcolor = Color.red; 
  int object;

  public void init() {
    d = getSize();
    x = d.width * 2 / 3 ;
    y = d.height - radius;
    x1 = d.width * 1/3;
    y1 = d.height - breadth;

  }
  
  public void update(Graphics g) {
    if (im == null) {
      im = createImage(d.width, d.height);
      offscreen = im.getGraphics();
    }
    offscreen.setColor(backgroundcolor);
    offscreen.fillRect(0,0,d.width,d.height); 
    if (x < radius || x > d.width - radius) {
      dx = -dx; 
    }
    if (y < radius || y > d.height - radius) {
      dy = -dy; 
    }
     x += dx; y += dy; 
    if (x1 < length || x1 > d.width - length)
    {
      dx1 = -dx1;
    }
    if (y1 < breadth || y1 > d.height - breadth/6)
    {
      dy1 = -dy1;
    }
    x1 += dx1;
    y1 += dy1;
   
    offscreen.setColor(ballcolor);
    offscreen.fillOval(x - radius, y - radius, radius * 2, radius * 2);

    offscreen.setColor(rectanglecolor);
    offscreen.fillRect(x1 - length, y1 - breadth, length*2, breadth);

    g.drawImage(im, 0, 0, this); 
    
    if(Math.sqrt((x1 - x) *(x1 - x)) - (radius + length * 3/4) <= 1)
    {
      dx = -dx;
      dy = -dy;
      dx1 = -dx1;
      dy1 = -dy1;
    }
 }
 
  public void paint(Graphics g) {
    update(g); 
  }
  public void setObject(int i) {
    object = i; 
  }
  
  public void setColor(Color c) 
  {
    if ( object == 0 && c != backgroundcolor)
    {
      ballcolor = c;
    }
    else if (object == 1 && c != backgroundcolor)
    {
       rectanglecolor =  c;
     }
    else if (object == 2 && c != rectanglecolor && c != ballcolor)
    {
      backgroundcolor = c;
     }
  }
}