import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;

public class Ball extends Applet implements Runnable, MouseListener {

  private Image img;
  private Thread ani;
  private int width,height;
  private Point dest;
  private Color ballC;
  

  public void init() {
   width=Integer.parseInt(getParameter("width"));
   height=Integer.parseInt(getParameter("height"));
   img=createImage(width,height);
  }

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

  public void paint(Graphics g) {
    g.drawImage(img,0,0,width,height,null);
  }

  public void update(Graphics g) {
    g.drawImage(img,0,0,width,height,null);
  }

  public void run(){
    int x=(int)(width/2);
    int y=(int)(height/2);
    Graphics g=img.getGraphics();
    g.setXORMode(getBackground());
    ballC=Color.red;
    while (true) {
      g.setColor(ballC);
      g.fillOval(x,y,30,30);
      repaint(x,y,30,30);
      try{ Thread.sleep(5); } catch (Exception e){}
      g.fillOval(x,y,30,30);
      repaint(x,y,30,30);
      if (dest == null) {
        x+=(int)(6*Math.random()-3);
        y+=(int)(6*Math.random()-3);
      } else{
        if (x!= dest.x) x+=(x>dest.x)?-1:1;
        if (y!= dest.y) y+=(y>dest.y)?-1:1;
        if (x == dest.x && y == dest.y) dest=null; 
      }
    }
  }

  public void mouseClicked(MouseEvent evt) {
    dest=evt.getPoint();
  }

  public void mousePressed(MouseEvent evt) { }

  public void mouseReleased(MouseEvent evt) { }

  public void mouseEntered(MouseEvent evt) {
    dest=evt.getPoint();
    ballC=Color.red;
  }

  public void mouseExited(MouseEvent evt) {
    dest=evt.getPoint();
    ballC=Color.blue;
  } 



}


