// Swarm.java // Written by THC for CS 5 Lab Assignment #2. // Maintains information about a swarm of bugs. import java.awt.*; public class Swarm { private Bug[] insects; // array of Bug objects private int bugCount; // only entries 0 to bugCount-1 reference existing Bug objects // Constructor. Given how many Bug objects we'll ever have at once, create // the array and initialize bugCount to 0. public Swarm(int howMany) { insects = new Bug[howMany]; bugCount = 0; } // Return how many Bugs currently exist. public int getBugCount() { return bugCount; } // Draw every Bug that currently exists. public void draw(Graphics page) { for (int i = 0; i < bugCount; i++) insects[i].draw(page); } // Move every Bug that currently exists. // Any Bug that moves fully off the top of the window no longer exists. public void move() { int thisBug = 0; // index into insects array while (thisBug < bugCount) { // Move a Bug. If it's still in the window, go on to the next one. // Otherwise, terminate this Bug. if (insects[thisBug].move()) thisBug++; // still in the window else terminate(thisBug); // moved fully off the top } } // Terminate a Bug. Do so by moving the last Bug that exists in the insects // array to the index of this Bug, making that last entry be null, and decrementing // bugCount. Note that this method works even if whichBug == bugCount-1. private void terminate(int whichBug) { insects[whichBug] = insects[bugCount-1]; insects[bugCount-1] = null; bugCount--; } // Add a new Bug to the Swarm, but only if there's room. public void add(Point where) { if (bugCount < insects.length) { // is there room? insects[bugCount] = new Bug(where); // yes, so add the Bug bugCount++; // and record that we've got one more } } // Hit all bugs that fall under a given Point. // All bugs whose bounding box contains the Point are terminated. public void hitBugs(Point where) { int thisBug = 0; // index into insects array while (thisBug < bugCount) { // See if this Bug is hit. // If not, then go on to the next one. // If it is hit, terminate this Bug. if (insects[thisBug].isHit(where)) terminate(thisBug); else thisBug++; } } }