// Agents.java import java.applet.Applet; import java.applet.AppletContext; import java.awt.*; import java.net.MalformedURLException; import java.net.URL; public class Agents extends Applet implements Runnable { public void assignRandomTargets (int mode) { for (int i = 0; i < MAXANTZ; i++) { int j; while ((j = (int)(Math.random() * (double)MAXANTZ)) == i) ; antz[i].SetTarget (antz[j]); antz[i].SetMode (mode); } } public void assignCircularTargets (int mode) { for (int i = 1; i < MAXANTZ; i++) { antz[i].SetTarget(antz[i-1]); antz[i].SetMode (mode); } antz[0].SetTarget (antz[MAXANTZ-1]); antz[0].SetMode (mode); } public void init () { _w = getWidth (); _h = getHeight (); _img = createImage (_w, _h); _gfx = _img.getGraphics (); Ant.SetBounds (_w, _h); setBackground (new Color (0x404040)); antz = new Ant [MAXANTZ]; for (int i = 0; i < MAXANTZ; i++) { antz[i] = new Ant(); antz[i].SetPosition (Math.random() * (double)_w, Math.random() * (double)_h); antz[i].SetMode (1); antz[i].SetColor (new Color (0xff6600)); } assignRandomTargets (1); } public void start () { if (_thr == null) {_thr = new Thread (this); _thr.start();} } public void run () { int i1 = 1000; _gfx.setColor (new Color (0x404040)); _gfx.fillRect (0, 0, _w, _h); repaint (); do { do { try {Thread.sleep (20L);} catch (InterruptedException interruptedexception) {} _gfx.setColor (new Color (0x404040)); _gfx.fillRect (0, 0, _w, _h); for (int j = 0; j < MAXANTZ; j++) { antz[j]._fx = 0D; antz[j]._fy = 0D; } for (int k = 0; k < MAXANTZ; k++) { for (int i = k + 1; i < MAXANTZ; i++) { double d1 = antz[i]._x - antz[k]._x; double d2 = antz[i]._y - antz[k]._y; if (d1 <= 6D && d1 >= -6D && d2 <= 6D && d2 >= -6D) { double d3 = d1 * d1; d3 += d2 * d2; if (d3 <= 36D) { antz[i]._fx += d1 * ( 6D / d3); antz[i]._fy += d2 * ( 6D / d3); antz[k]._fx += d1 * (-6D / d3); antz[k]._fy += d2 * (-6D / d3); } } } } for (int l = 0; l < MAXANTZ; l++) {antz[l].Think (); antz[l].Move (); antz[l].Display (_gfx);} repaint (); } while (--i1 != 0); double d = Math.random(); if (d < 0.25D) { i1 = (int)(Math.random()*500D + 200D); assignCircularTargets (1);} else if(d < 0.6D) { i1 = (int)(Math.random()*500D + 200D); assignRandomTargets (2);} else { i1 = (int)(Math.random()*500D + 100D); assignRandomTargets (1);} } while (true); } public void update (Graphics g) {paint (g);} public void paint (Graphics g) {g.drawImage (_img, 0, 0, this);} int _w, _h; Graphics _gfx; Image _img; Thread _thr; int MAXANTZ = 300; Ant antz []; }