Simple Bouncing Ball Program


[Up]

Source Code

import java.awt.Graphics;
import java.awt.Color;
import java.applet.Applet;

public class Ball extends Applet implements Runnable {
  Thread thr;
  int x = 20, y = 300, r = 7;
  int vx = 5, vy = 0, a = 3;
  double d = 0.88;
  
  public void init() {
    setBackground(Color.white);
  }
  public void start() {
    if (thr == null) {
      thr = new Thread(this);
      thr.start();
    }
  }
  public void run() {
    while(true) {
      x += vx; y -= vy;
      vy += a;
      if (x > 300) {
	x = 600-x; vx *= -1;
      }
      else if (x < 0) {
	x *= -1; vx *= -1;
      }
      if (y < 0) {
	y = (int)(-(double)y * d); vy = (int) (-(double) vy * d);
      }
      else if (y == 0 && vy == 0) {
	x = 20; y = 300;
      }
      repaint();
      try{
	Thread.sleep(50);
      }
      catch(InterruptedException e) { }
    }
  }
  public void paint(Graphics g) {
    g.setColor(Color.blue);
    g.fillOval(50+x-r, 380-y+r, 2*r, 2*r);
  }
  public void stop() {
    if (thr != null) {
      thr.stop();
      thr = null;
    }
  }
}

naniwa@rbt.his.fukui-u.ac.jp