// Swarm.java // Written by THC for CS 5 Lab Assignment #2. // Modified by Scot Drysdale to demostrate iterators. // Maintains information about a swarm of bugs. import java.awt.*; import java.util.ArrayList; import java.util.Iterator; public class Swarm { private ArrayList insects; // array of Bug objects // Constructor. Given how many Bug objects we'll ever have at once, create // the array and initialize bugCount to 0. // Note that this version ignores howMany. public Swarm(int howMany) { insects = new ArrayList(); } // Return how many Bugs currently exist. public int getBugCount() { return insects.size(); } // Draw every Bug that currently exists. // This version uses the foreach construct. public void draw(Graphics page) { for (Bug aBug: insects) aBug.draw(page); } // Move every Bug that currently exists. // Any Bug that moves fully off the top of the window no longer exists. // Because we remove bugs, we have to use an iterator rather than a for-all public void move() { Iterator iter = insects.iterator(); while (iter.hasNext()) { // Move a Bug. If it's still in the window, go on to the next one. // Otherwise, terminate this Bug. Bug thisBug = iter.next(); if (!thisBug.move()) iter.remove(); // moved fully off the top } } // Add a new Bug to the Swarm, but only if there's room. public void add(Point where) { insects.add(new Bug(where)); } // Hit all bugs that fall under a given Point. // All bugs whose bounding box contains the Point are terminated. public void hitBugs(Point where) { Iterator iter = insects.iterator(); while (iter.hasNext()) { if (iter.next().isHit(where)) // Was current bug hit? iter.remove(); // If so, remove it. } } }