ShipPool: rename ancestor->parent, make private
[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     private ShipPool parent;
15
16     private HashSet<Ship> allocatedShips = new HashSet<Ship>();
17
18     public ShipPool(Fleet fleet) { this(fleet, null); }
19     public ShipPool(ShipPool parent) { this(parent.fleet, parent); }
20     public ShipPool(Fleet fleet, ShipPool parent) {
21         this.fleet = fleet;
22         this.parent = parent;
23     }
24
25     public Iterator<Ship> iterator() { return allocatedShips.iterator(); }
26
27     public void allocateShip(Ship ship) {
28         if (allocatedShips.contains(ship))
29             throw new RuntimeException("already allocated!");
30         if (parent != null)
31             parent.allocateShip(ship);
32         allocatedShips.add(ship);
33     }
34
35     /** allocate a ship */
36     public Ship allocateShip(String type) {
37         Ship ship = null;
38         if (parent != null) {
39             ship = parent.allocateShip(type);
40         } else {
41             for(int i=0; ; i++) {
42                 ship = fleet.getShip(type, i);
43                 if (ship==null)
44                     throw new RuntimeException("no more ships of type " + type);
45                 if (!allocatedShips.contains(ship)) break;
46             }
47         }
48         allocatedShips.add(ship);
49         return ship;
50     }
51
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);
58     }
59
60     public void releaseAll() {
61         HashSet<Ship> toRelease = new HashSet<Ship>();
62         toRelease.addAll(allocatedShips);
63         for (Ship ship : toRelease)
64             releaseShip(ship);
65     }
66 }