import java.awt.*; import java.applet.*; /* */ public class MovingCircles extends BasicAnimationApplet { CircleSprite[] circles = new CircleSprite[10]; public void init() { int width = 100; // width of applet's window int height = 100; // height of applet's window for (int i = 0; i < circles.length; i++) { int x = randomIntBelow(width); int y = randomIntBelow(height); Color c = randomColor(); circles[i] = new CircleSprite(x, y, c); } } public void step() { for (int i = 0; i < circles.length; i++) circles[i].step(); } public void paint(Graphics g) { for (int i = 0; i < circles.length; i++) circles[i].paint(g); } Color randomColor() { Color[] colors = {Color.blue, Color.red, Color.green, Color.yellow}; int r = randomIntBelow(colors.length); return colors[r]; } int randomIntBelow(int n) { // Return a random number between 0 and one less than n. return (int) (Math.random() * n); } } class CircleSprite { int x, y; // the position of the circle int vx, vy; // the velocity Color color; CircleSprite(int xx, int yy, Color clr) { this.x = xx; this.y = yy; this.color = clr; vx = 2; vy = 0; } void step() { int width = 100; int height = 100; x += vx; y += vy; // wrap in all four directions if (x > width) x = 0; if (x < 0) x = width; if (y > height) y = 0; if (y < 0) y = height; } void paint(Graphics g) { int size = 10; g.setColor(color); g.fillOval(x, y, size, size); } }