// Collision detection test // // Author Matthew Caryl // Created 26.5.97 package Test; import java.awt.*; import java.applet.*; import ADT.*; public final class ObviousTest extends Applet implements Runnable { // // Private interface // private Thread animation; private Graphics graphics; private Random random = new Random(0); // // Public world interface // public void init() { setBackground(Color.black); // save graphics context for later // note: this seems to reduce garbage collection problems graphics = this.getGraphics(); } public void destroy() { if (animation != null && animation.isAlive()) animation.stop(); if (graphics != null) graphics.dispose(); super.destroy(); } public void start() { if (animation == null) { animation = new Thread(this); animation.start(); } else animation.resume(); } public void stop() { if (animation != null && animation.isAlive()) animation.suspend(); } public void run() { int width = size().width; // create 16 bots of radius 16 with positions in ([0..width-1], [0..width-1) Bot[] bots = obviousCreateBots(16, 16, width); while (true) { long ticks = System.currentTimeMillis(); erase(bots); obviousTick(bots, width); obviousCollision(bots); display(bots, Color.white); try { animation.sleep(Math.max(100, 100 - (System.currentTimeMillis() - ticks))); } catch (InterruptedException e) { // do nothing } } } public void erase(Bot[] bots) { graphics.setColor(Color.black); for (int i = bots.length - 1; i >= 0; i--) { Bot b = bots[i]; if (b.collision) graphics.fillOval(b.x - b.r / 2, b.y - b.r / 2, 2 * b.r, 2 * b.r); else graphics.drawOval(b.x - b.r / 2, b.y - b.r / 2, 2 * b.r, 2 * b.r); b.collision = false; } } public void display(Bot[] bots, Color color) { graphics.setColor(color); for (int i = bots.length - 1; i >= 0; i--) { Bot b = bots[i]; if (b.collision) graphics.fillOval(b.x - b.r / 2, b.y - b.r / 2, 2 * b.r, 2 * b.r); else graphics.drawOval(b.x - b.r / 2, b.y - b.r / 2, 2 * b.r, 2 * b.r); } } public Bot[] obviousCreateBots(int number, int radius, int range) { Bot[] bots = new Bot[(int) number]; for (int i = bots.length - 1; i >= 0; i--) { Bot b = new Bot(); b.x = random.range(range); b.y = random.range(range); b.r = radius; b.dx = random.range(15) - 7; b.dy = random.range(15) - 7; bots[i] = b; } return bots; } public void obviousTick(Bot[] bots, int range) { for (int i = bots.length - 1; i >= 0; i--) { Bot b = bots[i]; b.x = (b.x + b.dx) & (range - 1); b.y = (b.y + b.dy) & (range - 1); } } public void obviousCollision(Bot[] bots) { for (int i = bots.length - 1; i >= 0; i--) { Bot p = bots[i]; for (int j = i - 1; j >= 0; j--) { Bot q = bots[j]; int dx = (p.x - q.x); int dy = (p.y - q.y); int dr = (p.r + q.r); if (dx * dx + dy * dy <= dr * dr) { p.collision = true; q.collision = true; } } } } }