import java.awt.*;


public class BouncingBall5
    extends java.applet.Applet implements Runnable {

  protected Color color = Color.blue;
  protected int radius = 20;
  protected int length = 40;
  protected int breadth = 25;
  protected int x, y,x1,y1;
  protected int dx = -2, dy = -4, dx1=-4,dy1 =-4;
  protected Image image;
  protected Graphics offscreen;
  protected Dimension d;

  public void init() {
    String att = getParameter("delay");
    if (att != null) {
      delay = Integer.parseInt(att);
    }

    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) {
    // create the off-screen image buffer
    // if it is invoked the first time
    if (image == null) {
      image = createImage(d.width, d.height);
      offscreen = image.getGraphics();
    }

    // draw the background
    offscreen.setColor(Color.black);
    offscreen.fillRect(0,0,d.width,d.height);

    // adjust the position of the ball and the rectangle 
    // reverse the direction if it touches
    // any of the four sides
    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;

    // draw the ball
      offscreen.setColor(color);
      offscreen.fillOval(x - radius, y - radius,
                           radius * 2, radius * 2);

    //draw the rectangle 
    offscreen.setColor(Color.cyan);
    offscreen.fillRect(x1-length,y1-breadth,length*2,breadth);

    // copy the off-screen image to the screen
    g.drawImage(image, 0, 0, this);

    //reverse the direction if ball touches the rectangle
    if(Math.sqrt((x1 - x) * (x1 - x))-
                 (radius + length*3/4) <= 1)
    { 
      dx = -dx;
      dy = -dy;
      dy1 = -dy1;
      dx1 = -dx1;
   }
 }

  public void paint(Graphics g) {
    update(g);
  }

  // The animation applet idiom
  protected Thread bouncingThread;
  protected int delay = 100;

  public void start() {
    bouncingThread = new Thread(this);
    bouncingThread.start();
  }

  public void stop() {
    bouncingThread = null;
  }

  public void run() {
    while (Thread.currentThread() == bouncingThread) {
      try {
        Thread.currentThread().sleep(delay);
      } catch  (InterruptedException  e) {}
        repaint();
      }
    }
 }
