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 private ShipPool parent;
16 private HashSet<Ship> allocatedShips = new HashSet<Ship>();
18 public ShipPool(Fleet fleet) { this(fleet, null); }
19 public ShipPool(ShipPool parent) { this(parent.fleet, parent); }
20 public ShipPool(Fleet fleet, ShipPool parent) {
25 public Iterator<Ship> iterator() { return allocatedShips.iterator(); }
27 public void allocateShip(Ship ship) {
28 if (allocatedShips.contains(ship))
29 throw new RuntimeException("already allocated!");
31 parent.allocateShip(ship);
32 allocatedShips.add(ship);
35 /** allocate a ship */
36 public Ship allocateShip(String type) {
39 ship = parent.allocateShip(type);
42 ship = fleet.getShip(type, i);
44 throw new RuntimeException("no more ships of type " + type);
45 if (!allocatedShips.contains(ship)) break;
48 allocatedShips.add(ship);
52 /** release an allocated ship */
53 public void releaseShip(Ship ship) {
54 if (!allocatedShips.contains(ship))
55 throw new RuntimeException("ship " + ship + " released but was not allocated");
56 allocatedShips.remove(ship);
57 if (parent != null) parent.releaseShip(ship);
60 public void releaseAll() {
61 HashSet<Ship> toRelease = new HashSet<Ship>();
62 toRelease.addAll(allocatedShips);
63 for (Ship ship : toRelease)