e829c7cf5176c3ff8b518eacbc72230d80285b25
[fleet.git] / src / edu / berkeley / fleet / loops / ShipPool.java
1 package edu.berkeley.fleet.loops;
2 import java.util.*;
3 import edu.berkeley.fleet.api.*;
4 import static edu.berkeley.fleet.util.BitManipulations.*;
5
6 /**
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.
10  */
11 public class ShipPool implements Iterable<Ship> {
12
13     public final Fleet fleet;
14     public final ShipPool ancestor;
15
16     private HashSet<Ship> allocatedShips = new HashSet<Ship>();
17
18     public ShipPool(Fleet fleet) { this(fleet, null); }
19     public ShipPool(Fleet fleet, ShipPool ancestor) {
20         this.fleet = fleet;
21         this.ancestor = ancestor;
22     }
23
24     public Iterator<Ship> iterator() { return allocatedShips.iterator(); }
25
26     public void allocateShip(Ship ship) {
27         if (allocatedShips.contains(ship))
28             throw new RuntimeException("already allocated!");
29         allocatedShips.add(ship);
30     }
31
32     /** allocate a ship */
33     public Ship allocateShip(String type) {
34         Ship ship = null;
35         if (ancestor != null) {
36             ship = ancestor.allocateShip(type);
37         } else {
38             for(int i=0; ; i++) {
39                 ship = fleet.getShip(type, i);
40                 if (ship==null)
41                     throw new RuntimeException("no more ships of type " + type);
42                 if (!allocatedShips.contains(ship)) break;
43             }
44         }
45         allocatedShips.add(ship);
46         return ship;
47     }
48
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);
55     }
56
57 }