import java.applet.*; import java.awt.*; import java.util.*; public class Comet extends Applet implements Runnable{ Thread drawOval; boolean done; int Wwidth, Wheight; int numBalls = 20; ballType ball[]; class ballType{ Color colour; int x, y, radius, xi, yi, xii, yii, oldx, oldy; ballType(){ oldx = oldy = x = y = radius = 10; xi = yi = 0; xii = yii = 1; } ballType(int newx, int newy, int r){ oldx = newx; oldy = y = newy; radius = r; xi = yi = 0; xii = yii = 1; } void move(){ oldx = x; oldy = y; if(x + xi <= 0){ xi = - xi; xii = -1; yii = 2; }else if(x + xi >= Wwidth - radius){ xi = - xi; xii = 1; yii = -2; } if(y + yi <= 0){ yi = - yi; yii = -1; xii = 2; }else if(y + yi >= Wheight - radius){ yi = - yi; yii = 1; xii = -2; } x += xi; y += yi; xi += xii; yi += yii; } public void trail(ballType leader){ float deltax, deltay, length, ratio; oldx = x; oldy = y; deltax = x - leader.x; deltay = y - leader.y; length = (float)Math.sqrt(deltax * deltax + deltay * deltay) * 2; if(length > radius + leader.radius){ ratio = (float)(radius + leader.radius) / length; deltax *= ratio; deltay *= ratio; x = (int)(leader.x + deltax); y = (int)(leader.y + deltay); } } } public void init(){ int n; //////// find out what the width and height of the window is. //////// Wwidth = (new Integer(getParameter("width"))).intValue(); Wheight = (new Integer(getParameter("height"))).intValue(); //////// initialize the balls ////////// ball = new ballType[numBalls]; for(n = 0; n < numBalls; n++){ ball[n] = new ballType(); } ball[0].xii = 1; ball[0].yii = -1; ball[0].y = Wheight >> 1; ball[0].x = Wwidth >> 2; for(n = 1; n < numBalls; n++){ ball[n].radius = (int)((float)(numBalls - n) * ((float)ball[0].radius / (float)numBalls)); } for(n = 0; n < numBalls; n++){ ball[n].colour = new Color( 255 - (n + 1) * (255 / numBalls), 192 / (n + 1), 0 ); } ///////// initialize the drawing area ////////// setBackground(Color.black); setForeground(Color.black); ///////// start the animation thread ///////// drawOval = new Thread(this); drawOval.start(); } public void run(){ int n; while(true){ ball[0].move(); for(n = 1; n < numBalls; n++){ ball[n].trail(ball[n - 1]); } repaint(); try{ Thread.sleep(30); } catch(Exception e){ showStatus("Error: " + e.getMessage()); } } } public void paint(Graphics g){ int n; for(n = numBalls - 1; n >= 0; n--){ g.setColor(ball[n].colour); g.fillOval(ball[n].x, ball[n].y, ball[n].radius << 1, ball[n].radius << 1); } } }