import java.applet.*;
import java.awt.*;
import java.util.Random;
class Ball {
Graphics g;
int x;
int y;
int xmove; // x movement
int ymove; // y movement
int radius;
Color bColor;
private final Random generator = new Random();
public Ball(Color c,int width,int height) {
x = generator.nextInt(width);
y = generator.nextInt(height);
// calculate random direction (and speed)
xmove = generator.nextInt(5) + 1;
ymove = generator.nextInt(5) + 1;
radius = 10;
bColor = c;
}// end constructor Ball
public void paint(Graphics graphik) {
graphik.setColor(bColor);
graphik.fillOval(x - radius, y - radius, 2 * radius, 2 * radius);
}// end method paint
public void moveBall(int width,int height) {
if ((x - radius + xmove < 0) || (x + radius + xmove > width)) {
xmove = -xmove;
}
if ((y - radius + ymove < 0) || (y + radius + ymove > height)) {
ymove = -ymove;
}
// recalulate the x,y coordinates of the circle
x += xmove;
y += ymove;
}// end method moveBall
}// end class ball
public class BallsBounce extends Applet implements Runnable {
Thread th;
int numBalls;
Graphics graphic;
Image img;
Ball balls[];
private Color Colors[] = {Color.GRAY, Color.BLUE, Color.ORANGE, Color.CYAN, Color.BLACK, Color.MAGENTA, Color.GREEN, Color.PINK, Color.YELLOW, Color.RED};
int c = 0; // count the colors used
public void init() {
setBackground(Color.LIGHT_GRAY);
numBalls = Integer.parseInt(getParameter("balls"));
//
img = createImage(getWidth(), getHeight());
graphic = img.getGraphics();
balls = new Ball[numBalls];
for (int i = 0; i < numBalls; i++) {
if (c >= 10) {
c = 0;
}// end if
balls[i] = new Ball(Colors[c],getWidth(), getHeight());
c++;
}// end for
}// end method init
public void start() {
if (th == null) {
th = new Thread(this);
th.start();
}// end if
}// end method start
public void run() {
while (true) {
for (int j = 0; j < numBalls; j++) {
balls[j].moveBall(getWidth(), getHeight());
}// end for
try {
th.sleep(20);
}// end try
catch (InterruptedException except) {
}// end catch
repaint();
}// end while
}// end method run
public void paint(Graphics g) {
super.paint(g);
//g.clearRect(0, 0, this.getWidth(), this.getHeight());
graphic.clearRect(0, 0, this.getWidth(), this.getHeight());
for (int k = 0; k < numBalls; k++) {
balls[k].paint(graphic);
g.drawImage(img, 10, 10, this);
}// end for
}// end method paint
}// end class BallsBounce