CommandManager.java
1 package pep; 2 3 import hlt.*; 4 import java.util.Collection; 5 import java.util.HashMap; 6 import java.util.Map; 7 8 public class CommandManager { 9 private static HashMap<EntityId, Command> commands = new HashMap<>(); 10 private static Player me; 11 private static Game game; 12 private static GameMap gameMap; 13 14 public static void updateCommands(Game game){ 15 commands = new HashMap<>(); 16 CommandManager.me = game.me; 17 CommandManager.game = game; 18 CommandManager.gameMap = game.gameMap; 19 20 addMoves(getTargets()); 21 addSpawns(); 22 } 23 24 private static void addSpawns(){ 25 if (me.ships.size() == 0){ 26 commands.put(me.shipyard.id, Command.spawnShip()); 27 me.halite -= Constants.SHIP_COST; 28 gameMap.at(me.shipyard).markUnsafe(new Ship(me.id, EntityId.NONE, me.shipyard.position, 0)); 29 } 30 } 31 32 /** 33 * @return A map specifying the target position of each ship 34 */ 35 private static Map<EntityId, Position> getTargets() { 36 Map<EntityId, Position> targets = new HashMap<>(); 37 for (final Ship ship : me.ships.values()) { 38 if (!commands.containsKey(ship.id)){ 39 Behavior behavior = BehaviorManager.behaviorForShip(ship); 40 targets.put(ship.id, behavior.getTarget(ship, game)); 41 } 42 } 43 return targets; 44 } 45 46 /** 47 * Adds moves to the command queue based on target positions 48 */ 49 private static void addMoves(Map<EntityId, Position> targets){ 50 // add moves for ships 51 for (Map.Entry<EntityId, Position> entry : targets.entrySet()){ 52 Ship ship = me.ships.get(entry.getKey()); 53 Position target = entry.getValue(); 54 if (ship.position.equals(target) || !gameMap.canMove(ship)){ 55 commands.put(ship.id, ship.stayStill()); 56 } else { 57 Behavior behavior = BehaviorManager.behaviorForShip(ship); 58 Direction dir = gameMap.naiveNavigate(ship, target, behavior.minimizesCost()); 59 commands.put(ship.id, ship.move(dir)); 60 gameMap.at(ship.position).markSafe(); 61 } 62 } 63 } 64 65 public static void logCommands(){ 66 for (Command cmd : commands.values()) { 67 Log.log(cmd.command); 68 } 69 } 70 71 public static Collection<Command> getCommands(){ 72 return commands.values(); 73 } 74 }