1 package edu.berkeley.fleet.loops;
3 import edu.berkeley.fleet.api.*;
4 import static edu.berkeley.fleet.util.BitManipulations.*;
7 * A ShipPool keeps track of ships which have been "allocated" and
8 * are in use. ShipPools may be arranged in a hierarchy; allocating
9 * a ship in one pool will allocate it in all ancestors.
11 public class ShipPool implements Iterable<Ship> {
13 public final Fleet fleet;
14 public final ShipPool ancestor;
16 private HashSet<Ship> allocatedShips = new HashSet<Ship>();
18 public ShipPool(Fleet fleet) { this(fleet, null); }
19 public ShipPool(Fleet fleet, ShipPool ancestor) {
21 this.ancestor = ancestor;
24 public Iterator<Ship> iterator() { return allocatedShips.iterator(); }
26 /** allocate a ship */
27 public Ship allocateShip(String type) {
29 if (ancestor != null) {
30 ship = ancestor.allocateShip(type);
33 ship = fleet.getShip(type, i);
35 throw new RuntimeException("no more ships of type " + type);
36 if (!allocatedShips.contains(ship)) break;
39 allocatedShips.add(ship);
43 /** release an allocated ship */
44 public void releaseShip(Ship ship) {
45 if (!allocatedShips.contains(ship))
46 throw new RuntimeException("ship " + ship + " released but was not allocated");
47 allocatedShips.remove(ship);
48 if (ancestor != null) ancestor.releaseShip(ship);