import java.awt.*; import java.util.*; public class things extends BufferedApplet { final int N = 6; int w = 0, h = 0; Thing thing[] = new Thing[N]; Random rand = new Random(); Color offWhite = new Color(220,220,220); int n = -1; public void render(Graphics g) { if (w == 0) { w = bounds().width; h = bounds().height; for (int i = 0 ; i < N ; i++) { thing[i] = new Thing(); thing[i].x = w/2 + (rand.nextInt() % (w/2)); thing[i].y = h/2 + (rand.nextInt() % (h/2)); thing[i].r = w/20; } } g.setColor(offWhite); g.fillRect(0,0,w,h); for (int i = 0 ; i < N ; i++) { Thing T = thing[i]; // MAKE ME WIGGLE if (i != n) { T.dx += (rand.nextInt() % 2); T.dy += (rand.nextInt() % 2); double v = Math.sqrt(T.dx*T.dx + T.dy*T.dy); double maxV = 5; if (v > maxV) { T.dx *= maxV / v; T.dy *= maxV / v; } T.x += T.dx; T.y += T.dy; } // DON'T LET THEM CRAWL ALL OVER EACH OTHER for (int j = i+1 ; j < N ; j++) { Thing S = thing[j]; double dx = T.x - S.x; double dy = T.y - S.y; double d = Math.sqrt(dx*dx + dy*dy); if (d < T.r + S.r) { double f = (T.r + S.r - d) / (T.r + S.r); T.x += dx/2 * f; T.y += dy/2 * f; S.x -= dx/2 * f; S.y -= dy/2 * f; } } // DON'T LET ME ESCAPE if (T.x >= w-T.r) { T.x = w-T.r; T.dx = -T.dx; } if (T.y >= h-T.r) { T.y = h-T.r; T.dy = -T.dy; } if (T.x < T.r) { T.x = T.r; T.dx = -T.dx; } if (T.y < T.r) { T.y = T.r; T.dy = -T.dy; } // DRAW ME T.draw(g, i==n); } g.setColor(Color.black); g.drawRect(0,0,w-1,h-1); } public boolean mouseMove(Event e, int x, int y) { return true; } public boolean mouseDown(Event e, int x, int y) { return true; } public boolean mouseUp(Event e, int x, int y) { return true; } public boolean keyUp(Event e, int key) { switch (key) { case 'c': for (int i = 0 ; i < N ; i++) { thing[i].x = w/2; thing[i].y = h/2; } break; } return true; } public boolean mouseDrag(Event e, int x, int y) { int i; for (i = N-1 ; i >= 0 ; i--) if (thing[i].hit(x,y)) { thing[i].x = x; thing[i].y = y; break; } n = i; return true; } } class Thing { double dx, dy, x, y, r = 10; void draw(Graphics g, boolean isSelected) { g.setColor(isSelected ? Color.pink : Color.white); g.fillOval((int)(x-r), (int)(y-r), (int)(2*r), (int)(2*r)); g.setColor(Color.black); g.drawOval((int)(x-r), (int)(y-r), (int)(2*r), (int)(2*r)); } boolean hit(double x, double y) { double dx = this.x - x; double dy = this.y - y; return dx*dx + dy*dy <= r*r; } }