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(ShipPool ancestor) { this(ancestor.fleet, ancestor); }
20 public ShipPool(Fleet fleet, ShipPool ancestor) {
22 this.ancestor = ancestor;
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!");
30 allocatedShips.add(ship);
33 /** allocate a ship */
34 public Ship allocateShip(String type) {
36 if (ancestor != null) {
37 ship = ancestor.allocateShip(type);
40 ship = fleet.getShip(type, i);
42 throw new RuntimeException("no more ships of type " + type);
43 if (!allocatedShips.contains(ship)) break;
46 allocatedShips.add(ship);
50 /** release an allocated ship */
51 public void releaseShip(Ship ship) {
52 if (!allocatedShips.contains(ship))
53 throw new RuntimeException("ship " + ship + " released but was not allocated");
54 allocatedShips.remove(ship);
55 if (ancestor != null) ancestor.releaseShip(ship);
58 public void releaseAll() {
59 HashSet<Ship> toRelease = new HashSet<Ship>();
60 toRelease.addAll(allocatedShips);
61 for (Ship ship : toRelease)