import java.applet.*;
import java.awt.*;
import java.net.*;

public class Bounce extends Applet implements Runnable {
  Thread myThread;
  double x, y;
  int screenx, screeny;
  double vx, vy;
  double frac = .9;
  Image ball;
  boolean ballgrabbed=false;
  int grabx, graby;
  int lastx, lasty;

	public void init(){
	  try {
	    ball = getImage(new URL("http://www.mit.edu/people/mkgray/ball.gif"));
	  } catch(Exception e) { }
	  x = 50;
	  y = 50;
	  vx = 5;
	  vy = 5;
	}

	public void start(){
	  if(myThread == null){
	    myThread = new Thread(this);
	    myThread.start();
	  }
	}

	public void run(){
	  double tmpx, tmpy;
	  // First check for bounces
	    while(true){
	  tmpx = x+vx;
	  tmpy = y+vy;

	  if(tmpx > 200) {
	    tmpx = 200;
	    vx = (double) (-1*frac*vx);
	  }
	  else if(tmpx < 0 ){
	    tmpx = 0;
	    vx = (double) (-1*frac*vx);
	  }
	  if(tmpy > 200) {
	    tmpy = 200;
	    vy = (double) (-1*frac*vy);
	  }
	  else if(tmpy < 0 ){
	    tmpy = 0;
	    vy = (double) (-1*frac*vy);
	  }

	  if(tmpx == (x+vx)){
	    x = x+vx;
	  }
	  if(tmpy == (y+vy)){
	    y = y+vy;
	  }
	  
	  vy -= 1;
	  repaint();
	  try { Thread.sleep(100); } catch(Exception e) { }
	  while(ballgrabbed){
	  try { Thread.sleep(100); } catch(Exception e) { }
	  }
	    }
	    
	}

	public void stop(){
	  if(myThread != null){
	    myThread.stop();
	    myThread = null;
	  }
	}

	public synchronized boolean mouseUp(Event e, int mx, int my){
	  if(!ballgrabbed){
	    return true;
	  }

	  vx = (x-lastx);
	  vy = (y-lasty);
	  ballgrabbed = false;
	  return true;
	}

	public synchronized boolean mouseDrag(Event e, int mx, int my){
	  if(!ballgrabbed){
	    return true;
	  }
	  lastx = (int) x;
	  lasty = (int) y;
	  x = mx-grabx;
	  y = 200-(my-graby);
	  vx = 0; vy = 0;
	  repaint();
	  return true;
	}

	public synchronized boolean mouseDown(Event e, int mx, int my){
	  screenx = (int)x;
	  screeny = (int) (200.0-y);
	  if((mx > screenx) && (mx< (screenx+20)) &&(my>screeny) && (my<(screeny+20))){
	    ballgrabbed = true;
	    grabx = mx-screenx;
	    graby = my-screeny;
	    vx = 0;
	    vy = 0;
	  }
	  return true;
	}

	public void paint(Graphics g){
	  screenx = (int)x;
	  screeny = (int) (200.0-y);

	  g.drawImage(ball, screenx, screeny, this);
	}
}
