Example #1
0
  /**
   * Reverts the unit to the previous state, if possible.
   *
   * @return True if the reversion succeeds.
   */
  public boolean revert() {
    if (unit.isDisposed() || unit.getType() != type) return false;

    if (unit.getLocation() != loc) {
      unit.setLocation(loc);
    }
    if (unit.getWorkType() != work) {
      unit.setWorkType(work);
    }

    if (unit.getRole() != role) { // Try to restore role equipment.
      if (colony == null || unit.getColony() != colony) return false;
      Set<EquipmentType> eq = new HashSet<EquipmentType>();
      TypeCountMap<EquipmentType> unitEquipment = unit.getEquipment();
      eq.addAll(equipment.keySet());
      eq.addAll(unitEquipment.keySet());
      // Give back first, avoiding incompatible equipment problems.
      for (EquipmentType et : eq) {
        int count = equipment.getCount(et) - unitEquipment.getCount(et);
        if (count < 0) {
          unit.changeEquipment(et, count);
          colony.addEquipmentGoods(et, -count);
        }
      }
      for (EquipmentType et : eq) {
        int count = equipment.getCount(et) - unitEquipment.getCount(et);
        if (count > 0 && colony.canProvideEquipment(et) && unit.canBeEquippedWith(et)) {
          unit.changeEquipment(et, count);
          colony.addEquipmentGoods(et, -count);
        }
      }
    }
    return unit.getRole() == role;
  }
  /**
   * Tests that there is no over production of horses, to avoid them being thrown out. A test of the
   * proper production of horses is in <code>BuildingTest</code>
   */
  public void testNoHorsesOverProduction() {
    Game game = getGame();
    game.setMap(getTestMap());

    Colony colony = getStandardColony(1);

    Building pasture = colony.getBuilding(countryType);
    assertEquals(horsesType, pasture.getGoodsOutputType());
    assertEquals(
        "Wrong warehouse capacity in colony",
        GoodsContainer.CARGO_SIZE,
        colony.getWarehouseCapacity());

    // Still room for more
    colony.addGoods(horsesType, 99);
    assertTrue(colony.getNetProductionOf(foodType) > 0);

    assertEquals("Wrong horse production", 1, pasture.getTotalProductionOf(horsesType));
    assertEquals("Wrong maximum horse production", 1, pasture.getMaximumProductionOf(horsesType));
    assertEquals("Wrong net horse production", 1, colony.getNetProductionOf(horsesType));

    // No more room available
    colony.addGoods(horsesType, 1);
    assertEquals(
        "Wrong number of horses in colony",
        colony.getWarehouseCapacity(),
        colony.getGoodsCount(horsesType));
    assertEquals("Wrong horse production", 0, pasture.getTotalProductionOf(horsesType));
    assertEquals("Wrong maximum horse production", 0, pasture.getMaximumProductionOf(horsesType));
    assertEquals("Wrong net horse production", 0, colony.getNetProductionOf(horsesType));
  }
Example #3
0
  @Override
  public void buildShip(Integer colonyId) {
    Ship shipOnPlanet = null;

    Colony colony = colonyRepository.getColonyById(colonyId);
    Player player = colony.getPlayer();

    Game game = player.getGame();
    if (player.getCommandPoints() < BUILDSHIP_COST || player.isTurnEnded()) {
      throw new SpaceCrackNotAcceptableException(
          "Dear Sir or Lady, you have either run out of command points or your turn has ended, please wait for the other players to end their turn.");
    }
    for (Ship ship : player.getShips()) {
      if (ship.getPlanet().getName().equals(colony.getPlanet().getName())) {
        shipOnPlanet = ship;
      }
    }

    Ship ship;
    if (shipOnPlanet == null) {
      ship = new Ship();
      ship.setStrength(NEW_SHIP_STRENGTH);
      ship.setPlayer(player);
      ship.setPlanet(colony.getPlanet());
    } else {
      shipOnPlanet.setStrength(shipOnPlanet.getStrength() + NEW_SHIP_STRENGTH);
    }

    player.setCommandPoints(player.getCommandPoints() - BUILDSHIP_COST);
    gameSynchronizer.updateGame(game);
  }
Example #4
0
 /**
  * Record the state of a colony.
  *
  * @param colony The <code>Colony</code> to remember.
  */
 public ColonyWas(Colony colony) {
   this.colony = colony;
   this.population = colony.getUnitCount();
   this.productionBonus = colony.getProductionBonus();
   this.buildQueue = new ArrayList<BuildableType>(colony.getBuildQueue());
   if (colony.getGoodsContainer() != null) {
     colony.getGoodsContainer().saveState();
   }
 }
  public void testConsumers() {

    Game game = getGame();
    game.setMap(getTestMap());

    Colony colony = getStandardColony(3);
    int units = colony.getUnitCount();
    int buildings = colony.getBuildings().size();

    List<Consumer> consumers = colony.getConsumers();

    // units come first
    for (int index = 0; index < units; index++) {
      assertTrue(consumers.get(index).toString(), consumers.get(index) instanceof Unit);
    }
    // buildings come next
    for (int index = units; index < units + buildings; index++) {
      assertTrue(consumers.get(index).toString(), consumers.get(index) instanceof Building);
    }
    // build and population queues come last
    for (int index = units + buildings; index < units + buildings + 2; index++) {
      assertTrue(consumers.get(index).toString(), consumers.get(index) instanceof BuildQueue);
    }

    Building country = colony.getBuilding(countryType);
    assertTrue(consumers.contains(country));

    Building depot = colony.getBuilding(depotType);
    assertTrue(consumers.contains(depot));

    int countryIndex = consumers.indexOf(country);
    int depotIndex = consumers.indexOf(depot);
    assertTrue(countryIndex >= 0);
    assertTrue(depotIndex >= 0);
    assertTrue(
        "Priority of depot should be higher than that of country", depotIndex < countryIndex);

    BuildingType armoryType = spec().getBuildingType("model.building.armory");
    Building armory = new ServerBuilding(getGame(), colony, armoryType);
    colony.addBuilding(armory);
    consumers = colony.getConsumers();

    // units come first
    for (int index = 0; index < units; index++) {
      assertTrue(consumers.get(index).toString(), consumers.get(index) instanceof Unit);
    }
    int offset = units + buildings;
    // buildings come next
    for (int index = units; index < offset; index++) {
      assertTrue(consumers.get(index).toString(), consumers.get(index) instanceof Building);
    }
    // build queue comes last
    assertTrue(consumers.get(offset).toString(), consumers.get(offset) instanceof BuildQueue);
    // armory has a lower priority than the build queue
    assertTrue(consumers.get(offset + 1).toString(), consumers.get(offset + 1) instanceof Building);
    assertEquals(armoryType, ((Building) consumers.get(offset + 1)).getType());
    // population queue comes last
    assertTrue(
        consumers.get(offset + 2).toString(), consumers.get(offset + 2) instanceof BuildQueue);
  }
Example #6
0
 /**
  * Gets the operand value if it is applicable to the given Player.
  *
  * @param player The <code>Player</code> to check.
  * @return The operand value, or null if inapplicable.
  */
 public Integer getValue(Player player) {
   if (value == null) {
     if (scopeLevel == ScopeLevel.PLAYER) {
       List<FreeColObject> list = new LinkedList<FreeColObject>();
       switch (operandType) {
         case UNITS:
           list.addAll(player.getUnits());
           break;
         case BUILDINGS:
           for (Colony colony : player.getColonies()) {
             list.addAll(colony.getBuildings());
           }
           break;
         case SETTLEMENTS:
           list.addAll(player.getSettlements());
           break;
         case FOUNDING_FATHERS:
           list.addAll(player.getFathers());
           break;
         default:
           if (getMethodName() != null) {
             try {
               Method method = player.getClass().getMethod(getMethodName());
               if (method != null
                   && (int.class.equals(method.getReturnType())
                       || Integer.class.equals(method.getReturnType()))) {
                 return (Integer) method.invoke(player);
               }
             } catch (Exception e) {
               logger.warning(e.toString());
               return null;
             }
           }
           return null;
       }
       return count(list);
     } else if (scopeLevel == ScopeLevel.GAME) {
       return getValue(player.getGame());
     } else {
       return null;
     }
   } else {
     return value;
   }
 }
Example #7
0
 /**
  * Calculate the operand value within a given game.
  *
  * @param game The <code>Game</code> to check.
  * @return The operand value.
  */
 private Integer calculateGameValue(Game game) {
   switch (operandType) {
     case NONE:
       if (getMethodName() != null) {
         try {
           Method method = game.getClass().getMethod(getMethodName());
           if (method != null && Integer.class.isAssignableFrom(method.getReturnType())) {
             return (Integer) method.invoke(game);
           }
         } catch (Exception e) {
           logger.warning(e.toString());
         }
       }
       return null;
     case YEAR:
       return game.getTurn().getYear();
     case OPTION:
       return game.getSpecification().getInteger(getType());
     default:
       List<FreeColObject> list = new LinkedList<FreeColObject>();
       for (Player player : game.getPlayers()) {
         switch (operandType) {
           case UNITS:
             list.addAll(player.getUnits());
             break;
           case BUILDINGS:
             for (Colony colony : player.getColonies()) {
               list.addAll(colony.getBuildings());
             }
             break;
           case SETTLEMENTS:
             list.addAll(player.getSettlements());
             break;
           case FOUNDING_FATHERS:
             list.addAll(player.getFathers());
             break;
           default:
             return null;
         }
       }
       return count(list);
   }
 }
Example #8
0
 public void die() {
   goToNest = false;
   movementsMade = 0;
   discoveredFood.clear();
   Set<WorldGridSquare> nests = antColony.getNests();
   if (!nests.isEmpty()) {
     int nestIndex = (int) (nests.size() * Math.random());
     WorldGridSquare nest = (WorldGridSquare) nests.toArray()[nestIndex];
     this.x = nest.column;
     this.y = nest.row;
   }
 }
Example #9
0
 public String toString() {
   Tile tile = colony.getTile();
   String eqStr = "/";
   for (EquipmentType e : equipment.keySet()) {
     eqStr += e.toString().substring(16, 17);
   }
   String locStr =
       (loc == null)
           ? ""
           : (loc instanceof Building)
               ? Utils.lastPart(((Building) loc).getType().toString(), ".")
               : (loc instanceof ColonyTile)
                   ? tile.getDirection(((ColonyTile) loc).getWorkTile()).toString()
                   : (loc instanceof Tile) ? (loc.getId() + eqStr) : loc.getId();
   Location newLoc = unit.getLocation();
   String newEqStr = "/";
   for (EquipmentType e : unit.getEquipment().keySet()) {
     newEqStr += e.toString().substring(16, 17);
   }
   String newLocStr =
       (newLoc == null)
           ? ""
           : (newLoc instanceof Building)
               ? Utils.lastPart(((Building) newLoc).getType().toString(), ".")
               : (newLoc instanceof ColonyTile)
                   ? tile.getDirection(((ColonyTile) newLoc).getWorkTile()).toString()
                   : (newLoc instanceof Tile) ? (newLoc.getId() + newEqStr) : newLoc.getId();
   GoodsType newWork = unit.getWorkType();
   int newWorkAmount = (newWork == null) ? 0 : getAmount(newLoc, newWork);
   return String.format(
           "%-30s %-25s -> %-25s",
           unit.getId() + ":" + Utils.lastPart(unit.getType().toString(), "."),
           locStr
               + ((work == null || workAmount <= 0)
                   ? ""
                   : "("
                       + Integer.toString(workAmount)
                       + " "
                       + Utils.lastPart(work.toString(), ".")
                       + ")"),
           newLocStr
               + ((newWork == null || newWorkAmount <= 0)
                   ? ""
                   : "("
                       + Integer.toString(newWorkAmount)
                       + " "
                       + Utils.lastPart(newWork.toString(), ".")
                       + ")"))
       .trim();
 }
  public void testGetPotentialProduction() {
    Game game = getGame();
    game.setMap(getTestMap());

    Colony colony = getStandardColony(1);
    ColonyTile colonyTile = colony.getColonyTile(colony.getTile());
    assertNotNull(colonyTile);
    assertEquals(plainsType, colony.getTile().getType());
    Building townHall = colony.getBuilding(townHallType);
    assertNotNull(townHall);
    UnitType colonistType = spec().getDefaultUnitType();
    assertNotNull(colonistType);

    assertEquals(
        "Zero potential production of cotton in town hall",
        0,
        townHall.getPotentialProduction(cottonType, colonistType));
    assertEquals(
        "Basic potential production of bells in town hall",
        (int)
            FeatureContainer.applyModifiers(
                0f, game.getTurn(), townHall.getProductionModifiers(bellsType, colonistType)),
        townHall.getPotentialProduction(bellsType, colonistType));

    assertEquals(
        "Basic potential production of cotton on center tile" + " if not using a unit",
        plainsType.getProductionOf(cottonType, null),
        colonyTile.getPotentialProduction(cottonType, null));
    assertEquals(
        "Zero potential production of cotton on center tile" + " if using a unit",
        0,
        colonyTile.getPotentialProduction(cottonType, colonistType));
    assertEquals(
        "Zero potential production of cotton in town hall",
        0,
        townHall.getPotentialProduction(cottonType, colonistType));
  }
Example #11
0
 /**
  * Gets the operand value if it is applicable to the given Settlement.
  *
  * @param settlement The <code>Settlement</code> to check.
  * @return The operand value, or null if inapplicable.
  */
 public Integer getValue(Settlement settlement) {
   if (value == null) {
     if (scopeLevel == ScopeLevel.SETTLEMENT && settlement instanceof Colony) {
       Colony colony = (Colony) settlement;
       List<FreeColObject> list = new LinkedList<FreeColObject>();
       switch (operandType) {
         case UNITS:
           list.addAll(colony.getUnitList());
           break;
         case BUILDINGS:
           list.addAll(colony.getBuildings());
           break;
         default:
           if (getMethodName() != null) {
             try {
               Method method = colony.getClass().getMethod(getMethodName());
               if (method != null && Integer.class.isAssignableFrom(method.getReturnType())) {
                 return (Integer) method.invoke(colony);
               }
             } catch (Exception e) {
               logger.warning(e.toString());
               return null;
             }
           }
           return null;
       }
       return count(list);
     } else {
       // in future, we might expand this to handle native
       // settlements
       return null;
     }
   } else {
     return value;
   }
 }
  public void testProductionSoldier() {

    Game game = getStandardGame();
    Map map = getTestMap();
    game.setMap(map);
    Player dutch = game.getPlayer("model.nation.dutch");

    Tile tile = map.getTile(5, 8);
    Resource grain = new Resource(game, tile, spec().getResourceType("model.resource.grain"));
    tile.addResource(grain);

    UnitType veteran = spec().getUnitType("model.unit.veteranSoldier");
    Unit soldier = new ServerUnit(game, map.getTile(6, 8), dutch, veteran);

    Colony colony = new ServerColony(game, dutch, "New Amsterdam", soldier.getTile());
    dutch.addSettlement(colony);
    GoodsType foodType = grainType;
    soldier.setWorkType(foodType);
    nonServerBuildColony(soldier, colony);

    // Test the colony
    assertEquals(map.getTile(6, 8), colony.getTile());

    assertEquals("New Amsterdam", colony.getName());

    assertEquals(colony, colony.getTile().getSettlement());

    assertEquals(dutch, colony.getTile().getOwner());

    // Disabled.  Removal of equipment has moved to the server, so
    // nonServerBuildColony is not going to work.
    //// Should have 50 Muskets and nothing else
    // GoodsType muskets = spec().getGoodsType("model.goods.muskets");
    // assertNotNull(muskets);
    //
    // for (GoodsType type : spec().getGoodsTypeList()){
    //    if (type == muskets)
    //        assertEquals(50, colony.getGoodsCount(type));
    //    else
    //        assertEquals(type.toString(), 0, colony.getGoodsCount(type));
    // }

    // Test the state of the soldier
    // Soldier should be working on the field with the bonus

    assertEquals(foodType, soldier.getWorkType());

    assertEquals(colony.getColonyTile(tile).getTile(), soldier.getLocation().getTile());

    assertEquals(0, soldier.getMovesLeft());

    // assertEquals(false, soldier.isArmed());
  }
Example #13
0
 /** Fire any property changes resulting from actions within a colony. */
 public void fireChanges() {
   int newPopulation = colony.getUnitCount();
   if (newPopulation != population) {
     String pc = ColonyChangeEvent.POPULATION_CHANGE.toString();
     colony.firePropertyChange(pc, population, newPopulation);
   }
   int newProductionBonus = colony.getProductionBonus();
   if (newProductionBonus != productionBonus) {
     String pc = ColonyChangeEvent.BONUS_CHANGE.toString();
     colony.firePropertyChange(pc, productionBonus, newProductionBonus);
   }
   List<BuildableType> newBuildQueue = colony.getBuildQueue();
   if (!newBuildQueue.equals(buildQueue)) {
     String pc = ColonyChangeEvent.BUILD_QUEUE_CHANGE.toString();
     colony.firePropertyChange(pc, buildQueue, newBuildQueue);
   }
   if (colony.getGoodsContainer() != null) {
     colony.getGoodsContainer().fireChanges();
   }
 }
Example #14
0
  @Override
  public int createGame(Profile userProfile, String gameName, Profile opponentProfile) {
    Game game = new Game();

    Player player1 = new Player();
    Player player2 = new Player();

    userProfile.addPlayer(player1);
    opponentProfile.addPlayer(player2);

    player1.setCommandPoints(START_COMMAND_POINTS);
    player2.setCommandPoints(START_COMMAND_POINTS);

    player1.setRequestAccepted(true);
    player2.setRequestAccepted(false);

    player1.setGame(game);
    player2.setGame(game);

    Planet planetA = planetRepository.getPlanetByName("a");
    Planet planetA3 = planetRepository.getPlanetByName("a3");

    Ship player1StartingShip = new Ship(planetA);
    Ship player2StartingShip = new Ship(planetA3);

    player1StartingShip.setStrength(NEW_SHIP_STRENGTH);
    player2StartingShip.setStrength(NEW_SHIP_STRENGTH);

    player1StartingShip.setPlayer(player1);
    player2StartingShip.setPlayer(player2);

    Colony player1StartingColony = new Colony(planetA);
    Colony player2StartingColony = new Colony(planetA3);

    player1StartingColony.setStrength(NEW_COLONY_STRENGHT);
    player2StartingColony.setStrength(NEW_COLONY_STRENGHT);

    player1StartingColony.setPlayer(player1);
    player2StartingColony.setPlayer(player2);

    game.setName(gameName);

    gameRepository.createOrUpdateGame(game);

    return game.getGameId();
  }
  public void testBellNetProduction() {
    Game game = getStandardGame();

    game.setMap(getTestMap());

    Colony colony = getStandardColony(7);

    int initialBellCount = colony.getGoodsCount(bellsType);
    int expectedBellCount = 0;
    int bellsProdPerTurn = colony.getTotalProductionOf(bellsType);
    int expectedBellProd = 1;
    int bellsUpkeep = colony.getConsumptionOf(bellsType);
    int expectedBellUpkeep = colony.getUnitCount() - 2;
    int bellsNetProdPerTurn = colony.getNetProductionOf(bellsType);
    int expectedBellNetProd = expectedBellProd - expectedBellUpkeep;

    assertEquals("Wrong bell count", expectedBellCount, initialBellCount);
    assertEquals("Wrong bell production", expectedBellProd, bellsProdPerTurn);
    assertEquals("Wrong bell upkeep", expectedBellUpkeep, bellsUpkeep);
    assertEquals("Wrong bell net production", expectedBellNetProd, bellsNetProdPerTurn);
  }
Example #16
0
  /** Fire any property changes resulting from actions of a unit. */
  public void fireChanges() {
    UnitType newType = null;
    Unit.Role newRole = null;
    Location newLoc = null;
    GoodsType newWork = null;
    int newWorkAmount = 0;
    TypeCountMap<EquipmentType> newEquipment = null;
    if (!unit.isDisposed()) {
      newLoc = unit.getLocation();
      if (colony != null) {
        newType = unit.getType();
        newRole = unit.getRole();
        newWork = unit.getWorkType();
        newWorkAmount = (newWork == null) ? 0 : getAmount(newLoc, newWork);
        newEquipment = unit.getEquipment();
      }
    }

    if (loc != newLoc) {
      FreeColGameObject oldFcgo = (FreeColGameObject) loc;
      oldFcgo.firePropertyChange(change(oldFcgo), unit, null);
      if (newLoc != null) {
        FreeColGameObject newFcgo = (FreeColGameObject) newLoc;
        newFcgo.firePropertyChange(change(newFcgo), null, unit);
      }
    }
    if (colony != null) {
      if (type != newType && newType != null) {
        String pc = ColonyChangeEvent.UNIT_TYPE_CHANGE.toString();
        colony.firePropertyChange(pc, type, newType);
      } else if (role != newRole && newRole != null) {
        String pc = Tile.UNIT_CHANGE.toString();
        colony.firePropertyChange(pc, role.toString(), newRole.toString());
      }
      if (work == newWork) {
        if (work != null && workAmount != newWorkAmount) {
          colony.firePropertyChange(work.getId(), workAmount, newWorkAmount);
        }
      } else {
        if (work != null) {
          colony.firePropertyChange(work.getId(), workAmount, 0);
        }
        if (newWork != null) {
          colony.firePropertyChange(newWork.getId(), 0, newWorkAmount);
        }
      }
    }
    if (newEquipment != null) {
      Set<EquipmentType> keys = new HashSet<EquipmentType>();
      keys.addAll(equipment.keySet());
      keys.addAll(newEquipment.keySet());
      for (EquipmentType e : keys) {
        int cOld = equipment.getCount(e);
        int cNew = newEquipment.getCount(e);
        if (cOld != cNew) {
          unit.firePropertyChange(Unit.EQUIPMENT_CHANGE, cOld, cNew);
        }
      }
    }
    if (unit.getGoodsContainer() != null) {
      unit.getGoodsContainer().fireChanges();
    }
  }
  public void testProduction() {
    Game game = getGame();
    game.setMap(getTestMap());

    Colony colony = getStandardColony(3);
    ColonyTile tile = colony.getColonyTile(colony.getTile());

    assertEquals(0, colony.getGoodsCount(foodType));

    assertEquals(grainType, tile.getProduction().get(0).getType());
    assertEquals(5, tile.getProduction().get(0).getAmount());
    assertEquals(cottonType, tile.getProduction().get(1).getType());
    assertEquals(2, tile.getProduction().get(1).getAmount());

    for (Unit unit : colony.getUnitList()) {
      ProductionInfo unitInfo = colony.getProductionInfo(unit);
      assertNotNull(unitInfo);
      assertEquals(2, unitInfo.getConsumption().size());
      assertEquals(2, unitInfo.getMaximumConsumption().size());
      ProductionInfo tileInfo = colony.getProductionInfo(unit.getLocation());
      assertEquals(1, tileInfo.getProduction().size());
      assertEquals(grainType, tileInfo.getProduction().get(0).getType());
      assertEquals(5, tileInfo.getProduction().get(0).getAmount());
    }

    /*
    TypeCountMap<GoodsType> grossProduction = new TypeCountMap<GoodsType>();
    TypeCountMap<GoodsType> netProduction = new TypeCountMap<GoodsType>();
    for (ProductionInfo productionInfo : info.values()) {
        for (AbstractGoods goods : productionInfo.getProduction()) {
            grossProduction.incrementCount(goods.getType(), goods.getAmount());
            netProduction.incrementCount(goods.getType().getStoredAs(), goods.getAmount());
        }
        for (AbstractGoods goods : productionInfo.getStorage()) {
            grossProduction.incrementCount(goods.getType(), goods.getAmount());
            netProduction.incrementCount(goods.getType().getStoredAs(), goods.getAmount());
        }
        for (AbstractGoods goods : productionInfo.getConsumption()) {
            netProduction.incrementCount(goods.getType().getStoredAs(), -goods.getAmount());
        }
    }

    assertEquals(2, grossProduction.getCount(cottonType));
    assertEquals(2, colony.getNetProductionOf(cottonType));

    assertEquals(20, grossProduction.getCount(grainType));
    assertEquals(0, colony.getNetProductionOf(grainType));

    assertEquals(3, grossProduction.getCount(bellsType));
    assertEquals(0, colony.getNetProductionOf(bellsType));

    assertEquals(1, grossProduction.getCount(crossesType));
    assertEquals(1, colony.getNetProductionOf(crossesType));

    // this is storage only
    assertEquals(7, grossProduction.getCount(foodType));
    // this includes implicit type change and consumption
    assertEquals(14, colony.getNetProductionOf(foodType));

    colony.addGoods(horsesType, 50);
    colony.getUnitList().get(0).setWorkType(cottonType);
    Building weaverHouse = colony.getBuilding(spec().getBuildingType("model.building.weaverHouse"));
    colony.getUnitList().get(1).setLocation(weaverHouse);

    info = colony.getProductionAndConsumption();

    assertEquals(grainType, tile.getProduction().get(0).getType());
    assertEquals(5, tile.getProduction().get(0).getAmount());
    assertEquals(cottonType, tile.getProduction().get(1).getType());
    assertEquals(2, tile.getProduction().get(1).getAmount());

    grossProduction = new TypeCountMap<GoodsType>();
    netProduction = new TypeCountMap<GoodsType>();
    for (ProductionInfo productionInfo : info.values()) {
        for (AbstractGoods goods : productionInfo.getProduction()) {
            grossProduction.incrementCount(goods.getType(), goods.getAmount());
            netProduction.incrementCount(goods.getType().getStoredAs(), goods.getAmount());
        }
        for (AbstractGoods goods : productionInfo.getStorage()) {
            grossProduction.incrementCount(goods.getType(), goods.getAmount());
            netProduction.incrementCount(goods.getType().getStoredAs(), goods.getAmount());
        }
        for (AbstractGoods goods : productionInfo.getConsumption()) {
            netProduction.incrementCount(goods.getType().getStoredAs(), -goods.getAmount());
        }
    }

    assertEquals(4, grossProduction.getCount(cottonType));
    assertEquals(1, colony.getNetProductionOf(cottonType));

    assertEquals(3, grossProduction.getCount(clothType));
    assertEquals(3, colony.getNetProductionOf(clothType));

    assertEquals(10, grossProduction.getCount(grainType));
    assertEquals(0, colony.getNetProductionOf(grainType));

    assertEquals(2, grossProduction.getCount(horsesType));
    assertEquals(2, colony.getNetProductionOf(horsesType));

    assertEquals(3, grossProduction.getCount(bellsType));
    assertEquals(0, colony.getNetProductionOf(bellsType));

    assertEquals(1, grossProduction.getCount(crossesType));
    assertEquals(1, colony.getNetProductionOf(crossesType));

    // this is storage only
    assertEquals(2, grossProduction.getCount(foodType));
    // this includes implicit type change and consumption
    assertEquals(2, colony.getNetProductionOf(foodType));

    */
  }
Example #18
0
  public void step() {
    double chancetoTakeBest =
        Math.random(); // I don't like this, it s/b based upon pg. 222, but temp for random movement
    movementsMade++;

    discoveredFood.retainAll(antColony.getFood());

    if (this.goToNest) // has found ALL food and is working way back home.
    {
      if (this.antNetwork[this.x][this.y].hasNest()) die(); // ant "dies" upon return to the nest
      else {
        double currentMaxNestPheromone = 0;
        Map<WorldGridSquare, Double> maxFoodMap = new HashMap<WorldGridSquare, Double>();
        List<WorldGridSquare> maxNestGridSquaresList = new ArrayList<WorldGridSquare>();
        List<WorldGridSquare> allNeighborGridSquaresList = new ArrayList<WorldGridSquare>();
        double totalNeighborPheromones = 0;

        for (int c = -1; c <= 1; c++) {
          if (this.x + c < 0 || this.x + c >= antNetwork.length) continue;

          for (int r = -1; r <= 1; r++) {
            // ignore self, edges
            if (c == 0 && r == 0) continue;
            if (y + r < 0 || y + r >= antNetwork[0].length) continue;

            if (!antNetwork[this.x + c][this.y + r].isBlocked()) {
              allNeighborGridSquaresList.add(antNetwork[this.x + c][this.y + r]);
              totalNeighborPheromones += antNetwork[this.x + c][this.y + r].nestPheromoneLevel;

              if (antNetwork[this.x + c][this.y + r].getNestPheromoneLevel()
                  > currentMaxNestPheromone) {
                currentMaxNestPheromone =
                    antNetwork[this.x + c][this.y + r].getNestPheromoneLevel();
                maxNestGridSquaresList.clear();
                maxNestGridSquaresList.add(antNetwork[this.x + c][this.y + r]);
              } else if (antNetwork[this.x + c][this.y + r].getNestPheromoneLevel()
                  == currentMaxNestPheromone)
                maxNestGridSquaresList.add(antNetwork[this.x + c][this.y + r]);

              for (WorldGridSquare food : discoveredFood) {
                if (!maxFoodMap.containsKey(food)
                    || antNetwork[this.x + c][this.y + r].getFoodPheromoneLevel(food)
                        > maxFoodMap.get(food))
                  maxFoodMap.put(
                      food, antNetwork[this.x + c][this.y + r].getFoodPheromoneLevel(food));
              }
            }
          }
        }

        if (antNetwork[x][y].isFood())
          maxFoodMap.put(antNetwork[this.x][this.y], WorldGridSquare.maxFoodPheromoneLevel);

        for (WorldGridSquare food : discoveredFood) {
          antNetwork[this.x][this.y].setFoodPheromone(food, maxFoodMap.get(food) * Ant.dropOffRate);
        }

        // There's a % chance, essentially, that the Ant will choose the best route
        if (Ant.bestNextSquare > chancetoTakeBest) {
          if (!maxNestGridSquaresList.isEmpty()) {
            int randBestGSIndex = (int) (maxNestGridSquaresList.size() * Math.random());
            WorldGridSquare bestGridSquare = maxNestGridSquaresList.get(randBestGSIndex);

            this.x = bestGridSquare.column;
            this.y = bestGridSquare.row;
          }
        } else // if random didn't result in the best route, choose a (partially) random alternate
        {
          double currentPheromones = 0;
          double randPheromoneLevel = totalNeighborPheromones * Math.random();
          for (WorldGridSquare neighbor : allNeighborGridSquaresList) {
            currentPheromones += neighbor.getNestPheromoneLevel();
            if (currentPheromones > randPheromoneLevel) {
              this.x = neighbor.column;
              this.y = neighbor.row;
              break;
            }
          }
        }
      }
    } else // go hunting for food in the wild
    {
      if (antNetwork[this.x][this.y].isFood()) {
        discoveredFood.add(antNetwork[this.x][this.y]);
        if (discoveredFood.size() >= antColony.getFood().size()) {
          movementsMade = 0; // reset the track
          goToNest = true; // start heading home
          return;
        }
      } else if (antNetwork[this.x][this.y].hasNest()) {
        if (movementsMade > 1) {
          die();
          return;
        }
      }

      double currentMaxFoodPheromone = 0;
      double currentMaxNestPheromone = 0;

      Map<WorldGridSquare, Double> maxFoodMap = new HashMap<WorldGridSquare, Double>();
      List<WorldGridSquare> maxFoodGridSquaresList = new ArrayList<WorldGridSquare>();
      List<WorldGridSquare> allNeighborGridSquaresList = new ArrayList<WorldGridSquare>();
      double totalNeighborPheromones = 0;

      for (int c = -1; c <= 1; c++) {
        if (this.x + c < 0 || this.x + c >= antNetwork.length) continue;

        for (int r = -1; r <= 1; r++) {
          // ignore self, edges
          if (c == 0 && r == 0) continue;
          if (this.y + r < 0 || this.y + r >= antNetwork[0].length) continue;

          if (!antNetwork[this.x + c][this.y + r].isBlocked()) {
            allNeighborGridSquaresList.add(antNetwork[this.x + c][this.y + r]);

            if (currentMaxFoodPheromone == 0)
              maxFoodGridSquaresList.add(antNetwork[this.x + c][this.y + r]);

            for (WorldGridSquare food : discoveredFood) {
              if (!maxFoodMap.containsKey(food)
                  || antNetwork[this.x + c][this.y + r].getFoodPheromoneLevel(food)
                      > maxFoodMap.get(food))
                maxFoodMap.put(
                    food, antNetwork[this.x + c][this.y + r].getFoodPheromoneLevel(food));
            }

            if (antNetwork[this.x][this.y].isFood())
              maxFoodMap.put(antNetwork[this.x][this.y], WorldGridSquare.maxFoodPheromoneLevel);

            for (WorldGridSquare food : discoveredFood) {
              antNetwork[this.x][this.y].setFoodPheromone(
                  food, maxFoodMap.get(food) * Ant.dropOffRate);
            }

            if (antNetwork[this.x + c][this.y + r].getNestPheromoneLevel()
                > currentMaxNestPheromone) {
              currentMaxNestPheromone = antNetwork[this.x + c][this.y + r].getNestPheromoneLevel();
            }

            if (antColony.getFood().isEmpty()) totalNeighborPheromones += 1;
            else {
              for (WorldGridSquare food : antColony.getFood()) {
                if (discoveredFood.contains(food)) continue;

                totalNeighborPheromones +=
                    antNetwork[this.x + c][this.y + r].getFoodPheromoneLevel(food);

                if (antNetwork[this.x + c][this.y + r].getFoodPheromoneLevel(food)
                    > currentMaxFoodPheromone) {
                  currentMaxFoodPheromone =
                      antNetwork[this.x + c][this.y + r].getFoodPheromoneLevel(food);
                  maxFoodGridSquaresList.clear();
                  maxFoodGridSquaresList.add(antNetwork[this.x + c][this.y + r]);
                } else if (antNetwork[this.x + c][this.y + r].getFoodPheromoneLevel(food)
                    == currentMaxFoodPheromone) {
                  maxFoodGridSquaresList.add(antNetwork[this.x + c][this.y + r]);
                }
              }
            }
          }
        }
      }

      if (antNetwork[this.x][this.y].hasNest())
        currentMaxNestPheromone = WorldGridSquare.maxNestPheromoneLevel;

      antNetwork[this.x][this.y].setNestPheromone(currentMaxNestPheromone * Ant.dropOffRate);

      if (Ant.bestNextSquare > chancetoTakeBest) {
        if (!maxFoodGridSquaresList.isEmpty()) {
          int randBestGSIndex = (int) (maxFoodGridSquaresList.size() * Math.random());
          WorldGridSquare bestGridSquare = maxFoodGridSquaresList.get(randBestGSIndex);

          this.x = bestGridSquare.column;
          this.y = bestGridSquare.row;
        }
      } else // if random didn't result in the best route, choose a (partially) random alternate
      {
        double currentPheromones = 0;
        double randPheromoneLevel = totalNeighborPheromones * Math.random();

        for (WorldGridSquare neighbor : allNeighborGridSquaresList) {
          if (antColony.getFood().isEmpty()) {
            currentPheromones += 1;
            if (currentPheromones > randPheromoneLevel) {
              this.x = neighbor.column;
              this.y = neighbor.row;
              break;
            }
          } else {
            for (WorldGridSquare food : antColony.getFood()) {
              if (discoveredFood.contains(food)) continue;
              currentPheromones += neighbor.getFoodPheromoneLevel(food);
              if (currentPheromones > randPheromoneLevel) {
                this.x = neighbor.column;
                this.y = neighbor.row;
                break;
              }
            }
          }
        }
      }
    }
  }
  ColonyScreen(
      final Empire empire, final Colony colony, final int category, final Building building) {

    // Screen XXX
    this.setBounds(0, 0, resolutionX, resolutionY);
    this.add(GraphicFU.bgPanel, 0, 0);
    this.addMouseListener(getBack(empire, colony, category, building));
    this.topNavi = new TopNavi(empire);
    this.add(this.topNavi, 1, 0);

    JPanel colonyPanel = new JPanel();
    colonyPanel.setBounds(
        0, TopNavi.height, resolutionX, resolutionY - TopNavi.height - bottomPanelHeight);
    colonyPanel.setBorder(GUIBorder);
    colonyPanel.setLayout(new GridLayout(0, 3));
    colonyPanel.setOpaque(false);

    JPanel sliderPanel = new JPanel();
    sliderPanel.setOpaque(false);
    sliderPanel.setVisible(true);
    sliderPanel.setLayout(new GridLayout(0, 1));

    double maxAllocation = 0;

    for (int i = 0; i < 7; i++) {
      allocationSlider[i] = new AllocationSlider(allocationBarColor[i]);
      allocationSlider[i].setOpaque(false);
      allocationSlider[i].setVisible(true);
      allocationSlider[i].setLayout(new GridLayout());
      //	allocationSlider[i].setLayout(null);
      allocationSlider[i].addMouseListener(getSliderListener(empire, colony, category, building));
      allocationSlider[i].allocation = colony.allocation[i];
      allocationSlider[i].add(
          Labels.string((int) (allocationSlider[i].allocation * 1000) / 10.0 + "%"));
      sliderPanel.add(allocationSlider[i]);

      //	maxAllocation = Math.max(maxAllocation, allocationSlider[i].allocation);

    }

    allocationSlider[0].add(Labels.labourForceFood(colony));
    allocationSlider[1].add(Labels.labourForceResources(colony));
    allocationSlider[2].add(Labels.labourForceGoods(colony));
    allocationSlider[3].add(Labels.labourForceResearch(colony));
    allocationSlider[4].add(Labels.labourForceServices(colony));
    allocationSlider[5].add(Labels.labourForcePublicServices(colony));
    allocationSlider[6].add(
        Labels.label(
            (int) (colony.goods.stock * 10) / 10.0 + " " + language.abbrMegatons,
            GraphicFU.goodsIcon));

    // int distance = (int)((resolutionX -32) / 3 / (maxAllocation * 40.0 + 0.2));
    // System.out.print("Distance : " + distance);

    // for (int i = 0; i <7 ; i++){
    //		int pops = (int) (allocationSlider[i].allocation * 40.0 + 0.2);
    //		for (int j = 0; j < pops; j++ ){
    //	JLabel popIcon = Labels.icon(Species.rachni.speciesIcon);
    //			JLabel popIcon = Labels.icon(Species.humans.speciesIcon);
    //			popIcon.setToolTipText("Nr." + j);

    //	if (distance < 16){
    //		if ((j & 1) == 0){
    //			popIcon.setBounds(j * distance, 25, 40, 40);
    //			}
    //		else{
    //			popIcon.setBounds(j * distance, 0, 40, 40);
    //			}
    //		}
    //	else {
    //				popIcon.setBounds(j * distance, 10, 40, 40);
    //		}

    //		allocationSlider[i].add(popIcon);
    //		}
    //	}

    colonyPanel.add(sliderPanel);

    // LABELS XXX
    if (category >= 0 && category <= 7 && colony.getAvailableBuildings(category).size() > 0) {
      JScrollPane sp = ScrollPanes.buildingsAvailable(empire, colony, category, null);
      sp.addMouseListener(getBack(empire, colony, category, building));
      colonyPanel.add(sp);
    } else if (building != null) {
      JScrollPane sp = ScrollPanes.buildingDescription(empire, building);
      sp.addMouseListener(getBack(empire, colony, category, building));
      colonyPanel.add(sp);
    } else {
      JPanel dataPanel = new JPanel();
      dataPanel.setOpaque(false);
      dataPanel.setVisible(true);
      dataPanel.setLayout(new GridLayout(0, 1));

      for (int i = 0; i < 7; i++) {
        allocationPanel[i] = new JPanel();
        allocationPanel[i].setOpaque(false);
        allocationPanel[i].setLayout(new GridLayout());
        allocationPanel[i].addMouseListener(getBack(empire, colony, category, building));
        dataPanel.add(allocationPanel[i]);
      }

      //	allocationPanel[0].add(Labels.labourForceFood(colony),c);
      //	allocationPanel[1].add(Labels.labourForceResources(colony),c);
      //	allocationPanel[2].add(Labels.labourForceGoods(colony),c);
      //	allocationPanel[3].add(Labels.labourForceResearch(colony),c);
      //	allocationPanel[4].add(Labels.labourForceServices(colony),c);
      //	allocationPanel[5].add(Labels.labourForcePublicServices(colony),c);
      //	allocationPanel[6].add(Labels.labourForce(colony),c);

      //	allocationPanel[0].add(Labels.string((int)(colony.bProductivityFood * 1000) / 10.0 + "
      // %"),c);
      //	allocationPanel[1].add(Labels.string((int)(colony.bProductivityResources * 1000) / 10.0 + "
      // %"),c);
      //	allocationPanel[2].add(Labels.string((int)(colony.bProductivityGoods * 1000) / 10.0 + "
      // %"),c);
      //	allocationPanel[3].add(Labels.string((int)(colony.bProductivityResearch * 1000) / 10.0 + "
      // %"),c);
      //	allocationPanel[4].add(Labels.string((int)(colony.bWorkersServices	 * 1000) / 10.0 + "
      // %"),c);
      //	allocationPanel[5].add(Labels.string((int)(colony.bWorkersPublic * 1000) / 10.0 + " %"),c);

      allocationPanel[0].add(Labels.commodity(colony.commodity[0]));
      allocationPanel[1].add(Labels.commodity(colony.resources));
      allocationPanel[2].add(Labels.commodity(colony.goods));
      allocationPanel[3].add(
          Labels.label(
              (int) (colony.research.output * 10) / 10.0 + " " + language.abbrResearchUnits,
              GraphicFU.researchIcon));
      allocationPanel[4].add(
          Labels.label(
              (int) (colony.services.output * 10) / 10.0 + " " + language.abbrBillionCredits,
              GraphicFU.servicesIcon));
      allocationPanel[5].add(Labels.commodity(colony.money));
      allocationPanel[6].add(
          Labels.string((int) (colony.getGDP() * 10) / 10.0 + " " + language.abbrBillionCredits));

      if (colony.getBalanceFood() > 0) {
        allocationPanel[0].add(
            Labels.label(
                "+" + (int) (colony.getBalanceFood() * 10) / 10.0 + " " + language.abbrMegatons,
                GraphicFU.arrowUp2));
      } else if (colony.getBalanceFood() < 0) {
        allocationPanel[0].add(
            Labels.label(
                (int) (colony.getBalanceFood() * 10) / 10.0 + " " + language.abbrMegatons,
                GraphicFU.arrowDown2));
      } else {
        allocationPanel[0].add(
            Labels.label(
                (int) (colony.getBalanceFood() * 10) / 10.0 + " " + language.abbrMegatons,
                GraphicFU.arrowNeutral));
      }

      if (colony.getBalanceResources() > 0) {
        allocationPanel[1].add(
            Labels.label(
                "+"
                    + (int) (colony.getBalanceResources() * 10) / 10.0
                    + " "
                    + language.abbrMegatons,
                GraphicFU.arrowUp2));
      } else if (colony.getBalanceResources() < 0) {
        allocationPanel[1].add(
            Labels.label(
                (int) (colony.getBalanceResources() * 10) / 10.0 + " " + language.abbrMegatons,
                GraphicFU.arrowDown2));
      } else {
        allocationPanel[1].add(
            Labels.label(
                (int) (colony.getBalanceResources() * 10) / 10.0 + " " + language.abbrMegatons,
                GraphicFU.arrowNeutral));
      }

      if (colony.getBalanceGoods() > 0) {
        allocationPanel[2].add(
            Labels.label(
                "+" + (int) (colony.getBalanceGoods() * 10) / 10.0 + " " + language.abbrMegatons,
                GraphicFU.arrowUp2));
      } else if (colony.getBalanceGoods() < 0) {
        allocationPanel[2].add(
            Labels.label(
                (int) (colony.getBalanceGoods() * 10) / 10.0 + " " + language.abbrMegatons,
                GraphicFU.arrowDown2));
      } else {
        allocationPanel[2].add(
            Labels.label(
                (int) (colony.getBalanceGoods() * 10) / 10.0 + " " + language.abbrMegatons,
                GraphicFU.arrowNeutral));
      }

      allocationPanel[3].add(
          Labels.label(
              (int) (colony.innovation.output * 10) / 10.0 + " " + language.abbrResearchUnits,
              GraphicFU.innovationIcon));
      allocationPanel[4].add(
          Labels.label(
              (int) (colony.incomeAverage * 10000) / 10.0 + " " + "Cr./p", GraphicFU.moneyIcon));

      if (colony.getTax() - colony.getPublicExpenses() > 0) {
        allocationPanel[5].add(
            Labels.label(
                "+"
                    + (int) ((colony.getTax() - colony.getPublicExpenses()) * 10) / 10.0
                    + " "
                    + language.abbrBillionCredits,
                GraphicFU.arrowUp2));
      } else if (colony.getTax() - colony.getPublicExpenses() < 0) {
        allocationPanel[5].add(
            Labels.label(
                (int) ((colony.getTax() - colony.getPublicExpenses()) * 10) / 10.0
                    + " "
                    + language.abbrBillionCredits,
                GraphicFU.arrowDown2));
      } else {
        allocationPanel[5].add(
            Labels.label(
                (int) ((colony.getTax() - colony.getPublicExpenses()) * 10) / 10.0
                    + " "
                    + language.abbrBillionCredits,
                GraphicFU.arrowUp2));
      }

      allocationPanel[6].add(Labels.string((int) (colony.administration * 1000) / 10.0 + " %"));

      //	allocationPanel[0].add(Labels.string((int)(colony.getIncomeFood() * 10) / 10.0 + " " +
      // language.abbrBillionCredits),c);
      //	allocationPanel[1].add(Labels.string((int)(colony.getIncomeResources() * 10) / 10.0 + " " +
      // language.abbrBillionCredits),c);
      //	allocationPanel[2].add(Labels.string((int)(colony.getIncomeGoods() * 10) / 10.0 + " " +
      // language.abbrBillionCredits),c);
      //	allocationPanel[3].add(Labels.string((int)(colony.getIncomeResearch() * 10) / 10.0 + " " +
      // language.abbrBillionCredits),c);
      //	allocationPanel[4].add(Labels.string((int)(colony.getIncomeServices() * 10) / 10.0 + " " +
      // language.abbrBillionCredits),c);
      //	allocationPanel[5].add(Labels.string((int)(colony.getIncomePublicServices() * 10) / 10.0 +
      // " "  + language.abbrBillionCredits),c);
      //	allocationPanel[6].add(Labels.string((int)(colony.getGDP() * 10) / 10.0 + " " +
      // language.abbrBillionCredits),c);

      colonyPanel.add(dataPanel);
    }

    // BUILDINGS XXX

    JPanel buildingPanel = new JPanel();
    buildingPanel.setOpaque(false);
    buildingPanel.setVisible(true);
    buildingPanel.setLayout(new GridLayout(0, 1));

    JLabel buildOption[] = new JLabel[7];

    for (int i = 0; i < 7; i++) {
      buildingsPanel[i] = new JPanel();
      buildingsPanel[i].setOpaque(false);
      buildingsPanel[i].setLayout(new FlowLayout());
      buildingsPanel[i].addMouseListener(getBack(empire, colony, category, building));

      buildingsScroll[i] =
          new JScrollPane(
              buildingsPanel[i],
              ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER,
              ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
      buildingsScroll[i].setOpaque(false);
      buildingsScroll[i].getViewport().setOpaque(false);
      buildingsScroll[i].setWheelScrollingEnabled(true);
      buildingsScroll[i].getHorizontalScrollBar().setPreferredSize(new Dimension(0, 5));

      if (colony.getAvailableBuildings(i).size() > 0) {
        buildOption[i] = Labels.icon(GraphicFU.addIcon);
        buildOption[i].setBorder(new EmptyBorder(0, 0, 10, 0));
        buildOption[i].addMouseListener(getBuildOptionsML(empire, colony, i));
        buildingsPanel[i].add(buildOption[i]);
      }

      buildingPanel.add(buildingsScroll[i]);
    }

    for (int i = 0; i < 7; i++) {
      for (Building buildingX : colony.buildings) {
        if (buildingX.buildingType.classification == i) {
          BuildingButton bb = new BuildingButton(empire, buildingX);
          bb.setBorder(new EmptyBorder(0, 0, 15, 0));
          buildingsPanel[i].add(bb);
        }
      }
    }

    colonyPanel.add(buildingPanel);

    this.add(colonyPanel, 1, 0);

    // LABEL PANEL XXX

    this.add(new AODescriptionPanel(empire), 1, 0);

    this.topNavi.turnButton.addMouseListener(
        new MouseListener() {

          public void mouseClicked(MouseEvent e) {}

          public void mousePressed(MouseEvent e) {
            FUMain.mainFrame.openColonyScreen(empire, colony, category, building);
          }

          @Override
          public void mouseEntered(MouseEvent e) {}

          @Override
          public void mouseExited(MouseEvent e) {}

          @Override
          public void mouseReleased(MouseEvent e) {}
        });
  }