// The basic Bouncing Ball applet, from "Essential Java 2 Fast" by John Cowell,
// pages 216-217.

// <applet code="Bounce.class" width="320" height="220"> </applet>
import java.awt.*;
import java.applet.*;

public class Bounce extends Applet implements Runnable {
  double x, y, oldX, oldY;
  static double xLimit = 300;
  static double yLimit = 200;
  static Color backColor = Color.lightGray;
  boolean running = false;
  
  public void init() {
    setBackground(backColor);
    Thread runner = new Thread(this);
    runner.start();
  }
  
  public void run() {
    double xChange = Math.random();
    double yChange = Math.random();
    x = Math.random() * xLimit;
    y = Math.random() * yLimit;
    oldX = x;
    oldY = y;
    running = true;
    while (true) {
      x += xChange;
      y += yChange;
      if ((x >= xLimit) || (x <= 0)) xChange = -xChange;
      if ((y >= yLimit) || (y <= 0)) yChange = -yChange;
      repaint();
      try { Thread.sleep(1); }
      catch (InterruptedException e) { System.exit(0); }
    }
  }
  
  public void update(Graphics g) {
    paint(g);
  }
  
  public void paint(Graphics g) {
    if (!running) return;
    //erase the old ball by overwriting it
    g.setColor(backColor);
    g.fillOval((int)oldX, (int)oldY, 20, 20);
    //draw the new ball
    g.setColor(Color.red);
    g.fillOval((int)x, (int)y, 20, 20);
    // save the current co-ordinates so we can overwrite this ball next time
    oldX = x;
    oldY = y;
  }
}

