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

public class BearIO extends Applet 
                  implements Runnable, MouseListener, ImageObserver {

  private Point dest;
  private Thread anim;
  private Image bear, bearHappy, bearSad;
  private int bearX, bearY, height, width, imagesLoaded;
  private boolean applet=true;
  private Color bgcolor=new Color(0,170,170);
  
  public static void main(String[] args) {
    Frame f=new Frame("BearIO");
    f.setSize(300,300);
    f.addNotify();
    BearIO b=new BearIO();
    f.add(b);
    b.applet=false;
    b.init();
    f.setVisible(true);
  }

  public void init() {
   if (applet) {
     height=Integer.parseInt(getParameter("height"));
     width=Integer.parseInt(getParameter("width"));
     bearHappy=getImage(getCodeBase(),"bear_1.gif");
     bearSad=getImage(getCodeBase(),"bear_2.gif");
   } else {
     bearHappy=getToolkit().getImage("bear_1.gif");
     bearSad=getToolkit().getImage("bear_2.gif");
     height=300; width=300;
   }
   prepareImage(bearHappy,this);
   prepareImage(bearSad,this);
   addMouseListener(this);
   anim=new Thread(this);
   anim.start();
  }

  public void paint(Graphics g) {
    g.setColor(bgcolor);
    g.fillRect(0,0,width,height);
    if (bear!= null && imagesLoaded == 2)  {
      g.drawImage(bear,
                  bearX,bearY,
                  bear.getWidth(null),bear.getHeight(null),
                  null);
    } 
  }

  public void update(Graphics g) {
    paint(g);
  }

  public void run() { }

  public void go(){
    bearX=height/2;
    bearY=width/2;
    while (true) {
      repaint();
      try{ Thread.sleep(25); } catch (Exception e){}
      if (bear != null) {
        if (dest == null) {
          try{ Thread.sleep(100); } catch (Exception e){}
          bearX+=(int)(12*Math.random()-6);
          bearY+=(int)(12*Math.random()-6);
        } else{
          if (bearX!= dest.x) bearX+=(bearX>dest.x)?-1:1;
          if (bearY!= dest.y) bearY+=(bearY>dest.y)?-1:1;
          if (bearX == dest.x && bearY == 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();
    bear=bearHappy; 
  }

  public void mouseExited(MouseEvent evt) {
    dest=evt.getPoint();
    bear=bearSad;
  } 

  public boolean imageUpdate(Image img, int infoflags, int x, int y,
                             int width, int height) {
System.out.print(infoflags+" ");
    if (infoflags == ImageObserver.ALLBITS) {
      imagesLoaded++;
System.out.println();
      if (imagesLoaded == 2) go(); 
      return false;
    } else return true;
  }

}


