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 public void allocateShip(Ship ship) {
27 if (allocatedShips.contains(ship))
28 throw new RuntimeException("already allocated!");
29 allocatedShips.add(ship);
32 /** allocate a ship */
33 public Ship allocateShip(String type) {
35 if (ancestor != null) {
36 ship = ancestor.allocateShip(type);
39 ship = fleet.getShip(type, i);
41 throw new RuntimeException("no more ships of type " + type);
42 if (!allocatedShips.contains(ship)) break;
45 allocatedShips.add(ship);
49 /** release an allocated ship */
50 public void releaseShip(Ship ship) {
51 if (!allocatedShips.contains(ship))
52 throw new RuntimeException("ship " + ship + " released but was not allocated");
53 allocatedShips.remove(ship);
54 if (ancestor != null) ancestor.releaseShip(ship);