/** Tests invalid completion of buildable, having enough resources */
  public void testInvalidCompletion() {
    Game game = ServerTestHelper.startServerGame(getTestMap(true));

    Colony colony = getStandardColony(2);
    Building carpenterHouse = colony.getBuilding(carpenterHouseType);
    assertEquals(
        "Colony should not have lumber mill", carpenterHouse, colony.getBuilding(lumberMillType));
    assertFalse("Colony should not be able to build lumber mill", colony.canBuild(lumberMillType));
    colony.setCurrentlyBuilding(lumberMillType);
    assertEquals(
        "Colony should be building lumber mill", lumberMillType, colony.getCurrentlyBuilding());
    // Add sufficient units and goods to build lumber mill.
    Unit unit = new ServerUnit(game, colony.getTile(), colony.getOwner(), colonistType);
    unit.setLocation(colony);
    for (AbstractGoods ag : lumberMillType.getRequiredGoods()) {
      GoodsType type = ag.getType();
      int amount = ag.getAmount() + 1;
      colony.addGoods(type, amount);
      assertEquals("Wrong quantity of " + type, amount, colony.getGoodsCount(type));
    }

    // Allow the building to finish
    ServerTestHelper.newTurn();

    assertEquals(
        "Colony should have lumber mill",
        lumberMillType,
        colony.getBuilding(lumberMillType).getType());
    assertFalse(
        "Colony should no longer be building lumber mill",
        colony.getCurrentlyBuilding() == lumberMillType);
  }
  /**
   * The time to teach somebody does not depend on the one who is being taught, but on the teacher.
   */
  public void testTeachPettyCriminalsByMaster() {
    boolean selection = FreeColTestUtils.setStudentSelection(false);
    Game game = ServerTestHelper.startServerGame(getTestMap(true));

    Colony colony = getSchoolColony(4, SchoolLevel.UNIVERSITY);
    Building university = colony.getBuilding(universityType);
    Iterator<Unit> units = colony.getUnitIterator();

    Unit criminal = units.next();
    criminal.setType(pettyCriminalType);
    criminal.setLocation(colony.getBuilding(townHallType));

    Unit teacher = units.next();
    teacher.setType(masterBlacksmithType);

    teacher.setLocation(university);
    assertEquals(teacher.getNeededTurnsOfTraining(), 4);
    assertEquals(criminal, teacher.getStudent());

    trainForTurns(colony, teacher.getNeededTurnsOfTraining());
    assertEquals(0, getUnitList(colony, pettyCriminalType).size());
    assertEquals(indenturedServantType, criminal.getType());

    FreeColTestUtils.setStudentSelection(selection);
  }
  public void testAvoidStarvation() {
    Game game = ServerTestHelper.startServerGame(getTestMap(marsh));

    int unitsBeforeNewTurn = 3;
    Colony colony = getStandardColony(unitsBeforeNewTurn);
    ServerPlayer player = (ServerPlayer) colony.getOwner();
    assertEquals("Wrong number of units in colony", unitsBeforeNewTurn, colony.getUnitCount());

    final Building townHall = colony.getBuilding(townHallType);
    for (Unit u : colony.getUnitList()) {
      u.setLocation(townHall);
    }
    colony.removeGoods(foodGoodsType);
    colony.invalidateCache();

    int consumption = colony.getFoodConsumption();
    int production = colony.getTile().getType().getPotentialProduction(grainType, null);
    assertEquals(6, consumption);
    assertEquals(3, production);
    assertEquals(-3, colony.getNetProductionOf(foodType));
    assertEquals(0, colony.getGoodsCount(foodType));
    assertEquals(0, colony.getTile().getUnitCount());

    colony.addGoods(foodType, 202);
    ServerTestHelper.newTurn();
    assertEquals(199, colony.getGoodsCount(foodType));
    assertEquals(0, colony.getTile().getUnitCount());
    assertEquals(3, colony.getUnitCount());

    colony.addGoods(foodType, 15);
    ServerTestHelper.newTurn();
    assertEquals(11, colony.getGoodsCount(foodType));
    assertEquals(1, colony.getTile().getUnitCount());
  }
  public void testNoBuildingMaterialsProductionWhenBuildingNothing() {
    Game game = getGame();
    game.setMap(getTestMap(true));

    Colony colony = getStandardColony(4);
    Building carpenterHouse = colony.getBuilding(carpenterHouseType);
    Unit unit = colony.getFirstUnit();
    // necessary for work production
    int initialLumber = 100;
    int initialHammers = 0;
    colony.addGoods(lumberGoodsType, initialLumber);
    colony.setCurrentlyBuilding(null);

    assertEquals(
        "Wrong initial lumber quantity.", initialLumber, colony.getGoodsCount(lumberGoodsType));
    assertEquals(
        "Colony should not have initial hammers.",
        initialHammers,
        colony.getGoodsCount(hammerGoodsType));

    unit.setLocation(carpenterHouse);

    assertTrue(
        "Colony should be producing hammers.", colony.getTotalProductionOf(hammerGoodsType) > 0);

    ServerTestHelper.newTurn();

    assertEquals(
        "Colony should not have produced hammers.",
        initialHammers,
        colony.getGoodsCount(hammerGoodsType));
    assertEquals(
        "Wrong final lumber quantity.", initialLumber, colony.getGoodsCount(lumberGoodsType));
  }
  /**
   * Assign a carrier for this treasure.
   *
   * @param lb A <code>LogBuilder</code> to log to.
   * @return A suitable carrier <code>AIUnit</code>, to which this unit has been queued for
   *     transport.
   */
  private AIUnit assignCarrier(LogBuilder lb) {
    final AIUnit aiUnit = getAIUnit();
    final Unit unit = getUnit();
    final Player player = unit.getOwner();
    final Europe europe = player.getEurope();

    List<Unit> carriers = player.getCarriersForUnit(unit);
    if (carriers.isEmpty()) return null;

    // Pick the closest carrier and queue this unit.
    final Location here = unit.getLocation();
    int turns = INFINITY;
    Unit closest = null;
    for (Unit c : carriers) {
      int t = c.getTurnsToReach(here);
      if (turns > t) {
        turns = t;
        closest = c;
      }
    }
    final AIMain aiMain = getAIMain();
    TransportMission tm;
    AIUnit aiCarrier;
    if (closest != null
        && (aiCarrier = aiMain.getAIUnit(closest)) != null
        && (tm = aiCarrier.getMission(TransportMission.class)) != null) {
      setTarget(europe);
      aiUnit.changeTransport(aiCarrier);
      if (tm.forceCollection(aiUnit, lb)) {
        lb.add(" forced collection on ", aiCarrier.getUnit());
        return aiCarrier;
      }
    }
    return null;
  }
Beispiel #6
0
  /**
   * Handle a "buildColony"-message.
   *
   * @param server The <code>FreeColServer</code> handling the request.
   * @param player The <code>Player</code> building the colony.
   * @param connection The <code>Connection</code> the message is from.
   * @return An update <code>Element</code> defining the new colony and updating its surrounding
   *     tiles, or an error <code>Element</code> on failure.
   */
  public Element handle(FreeColServer server, Player player, Connection connection) {
    Game game = server.getGame();
    ServerPlayer serverPlayer = server.getPlayer(connection);

    Unit unit;
    try {
      unit = player.getFreeColGameObject(builderId, Unit.class);
    } catch (Exception e) {
      return DOMMessage.clientError(e.getMessage());
    }
    if (!unit.canBuildColony()) {
      return DOMMessage.clientError("Unit " + builderId + " can not build colony.");
    }

    if (colonyName == null) {
      return DOMMessage.clientError("Null colony name");
    } else if (Player.ASSIGN_SETTLEMENT_NAME.equals(colonyName)) {; // ok
    } else if (game.getSettlement(colonyName) != null) {
      return DOMMessage.clientError("Non-unique colony name " + colonyName);
    }

    Tile tile = unit.getTile();
    if (!player.canClaimToFoundSettlement(tile)) {
      return DOMMessage.clientError("Can not build colony on tile: " + tile);
    }

    // Build can proceed.
    return server.getInGameController().buildSettlement(serverPlayer, unit, colonyName);
  }
Beispiel #7
0
  /**
   * Handle a "deliverGift"-message.
   *
   * @param server The <code>FreeColServer</code> handling the message.
   * @param player The <code>Player</code> the message applies to.
   * @param connection The <code>Connection</code> message was received on.
   * @return An update containing the unit and settlement, or an error <code>Element</code> on
   *     failure.
   */
  public Element handle(FreeColServer server, Player player, Connection connection) {
    ServerPlayer serverPlayer = server.getPlayer(connection);

    Unit unit;
    try {
      unit = player.getFreeColGameObject(unitId, Unit.class);
    } catch (Exception e) {
      return DOMMessage.clientError(e.getMessage());
    }

    Settlement settlement;
    try {
      settlement = unit.getAdjacentSettlementSafely(settlementId);
    } catch (Exception e) {
      return DOMMessage.clientError(e.getMessage());
    }

    // Make sure we are trying to deliver something that is there
    if (goods.getLocation() != unit) {
      return DOMMessage.createError("server.trade.noGoods", "deliverGift of non-existent goods");
    }

    // Proceed to deliver.
    return server
        .getInGameController()
        .deliverGiftToSettlement(serverPlayer, unit, settlement, goods);
  }
  public void testIsTargetValidForSeekAndDestroy() {
    Game game = ServerTestHelper.startServerGame(getTestMap());
    Map map = game.getMap();
    AIMain aiMain = ServerTestHelper.getServer().getAIMain();

    // Create player and unit
    ServerPlayer incaPlayer = (ServerPlayer) game.getPlayerByNationId("model.nation.inca");
    NativeAIPlayer aiInca = (NativeAIPlayer) aiMain.getAIPlayer(incaPlayer);
    ServerPlayer dutchPlayer = (ServerPlayer) game.getPlayerByNationId("model.nation.dutch");

    Tile dutchUnitTile = map.getTile(9, 9);
    Tile braveUnitTile = map.getTile(9, 8);
    ;

    Unit brave = new ServerUnit(game, braveUnitTile, incaPlayer, braveType);
    Unit soldier = new ServerUnit(game, dutchUnitTile, dutchPlayer, veteranType);

    Player.makeContact(incaPlayer, dutchPlayer);

    assertFalse(
        "Target should NOT be valid for UnitSeekAndDestroyMission",
        aiInca.isTargetValidForSeekAndDestroy(brave, soldier.getTile()));

    incaPlayer.setTension(dutchPlayer, new Tension(Tension.Level.HATEFUL.getLimit()));
    assertTrue(
        "Target should be valid for UnitSeekAndDestroyMission",
        aiInca.isTargetValidForSeekAndDestroy(brave, soldier.getTile()));

    incaPlayer.setStance(dutchPlayer, Stance.WAR);
    dutchPlayer.setStance(incaPlayer, Stance.WAR);
    assertTrue(
        "Target should be valid for UnitSeekAndDestroyMission",
        aiInca.isTargetValidForSeekAndDestroy(brave, soldier.getTile()));
  }
 /**
  * Why would this mission be invalid with the given unit?
  *
  * @param aiUnit The <code>AIUnit</code> to test.
  * @return A reason why the mission would be invalid with the unit, or null if none found.
  */
 private static String invalidMissionReason(AIUnit aiUnit) {
   String reason = invalidAIUnitReason(aiUnit);
   if (reason != null) return reason;
   final Unit unit = aiUnit.getUnit();
   return (!unit.canCarryTreasure())
       ? "unit-cannot-carry-treasure"
       : (unit.getTreasureAmount() <= 0) ? "unit-treasure-nonpositive" : null;
 }
Beispiel #10
0
 /**
  * Returns a list of all units in this colony of the given type.
  *
  * @param type The type of the units to include in the list. For instance Unit.EXPERT_FARMER.
  * @return A list of all the units of the given type in this colony.
  */
 private List<Unit> getUnitList(Colony colony, UnitType type) {
   List<Unit> units = new ArrayList<>();
   for (Unit unit : colony.getUnitList()) {
     if (type.equals(unit.getType())) {
       units.add(unit);
     }
   }
   return units;
 }
  /** {@inheritDoc} */
  @Override
  public Mission doMission(LogBuilder lb) {
    lb.add(tag);
    String reason = invalidReason();
    if (isTargetReason(reason)) {
      return retargetMission(reason, lb);
    } else if (reason != null) {
      return lbFail(lb, false, reason);
    }

    for (; ; ) {
      // Go to the target.
      final Unit unit = getUnit();
      Unit.MoveType mt =
          travelToTarget(getTarget(), CostDeciders.avoidSettlementsAndBlockingUnits(), lb);
      switch (mt) {
        case MOVE: // Arrived
          break;

        case MOVE_HIGH_SEAS:
        case MOVE_NO_MOVES:
        case MOVE_NO_REPAIR:
        case MOVE_ILLEGAL:
          return lbWait(lb);

        case MOVE_NO_ACCESS_EMBARK:
        case MOVE_NO_TILE:
          return this;

        default:
          return lbMove(lb, mt);
      }

      // Cash in now if:
      // - already in Europe
      // - or can never get there
      // - it is free to transport the treasure
      // - or there is no potential carrier to get the treasure to there
      // Otherwise, it is better to send to Europe.
      lbAt(lb);
      final AIUnit aiUnit = getAIUnit();
      final Europe europe = getUnit().getOwner().getEurope();
      if (unit.canCashInTreasureTrain()) {
        AIUnit aiCarrier = null;
        boolean cashin = unit.isInEurope() || europe == null || unit.getTransportFee() == 0;
        if (!cashin && aiUnit.getTransport() == null) {
          cashin = assignCarrier(lb) == null;
        }
        if (cashin)
          return (AIMessage.askCashInTreasureTrain(aiUnit))
              ? lbDone(lb, false, "cashed in")
              : lbFail(lb, false, "cashin");
      }
      return retargetMission("transport expected", lb);
    }
  }
Beispiel #12
0
  /** Test that an indentured servant becomes a free colonist */
  public void testTeachIndenturedServants() {
    boolean selection = FreeColTestUtils.setStudentSelection(false);
    Game game = ServerTestHelper.startServerGame(getTestMap(true));

    Colony colony = getSchoolColony(4, SchoolLevel.UNIVERSITY);
    Building university = colony.getBuilding(universityType);
    Iterator<Unit> units = colony.getUnitIterator();

    Unit indenturedServant = units.next();
    indenturedServant.setType(indenturedServantType);

    Unit teacher = units.next();
    teacher.setType(masterBlacksmithType);

    teacher.setLocation(university);
    assertEquals(teacher.getNeededTurnsOfTraining(), 4);
    assertEquals(indenturedServant, teacher.getStudent());

    // Train to become free colonist
    trainForTurns(colony, teacher.getNeededTurnsOfTraining());
    assertEquals(0, getUnitList(colony, indenturedServantType).size());
    assertEquals(freeColonistType, indenturedServant.getType());

    FreeColTestUtils.setStudentSelection(selection);
  }
Beispiel #13
0
  public void testUniversity() {
    Game game = ServerTestHelper.startServerGame(getTestMap(true));

    // otherwise this test will crash and burn
    boolean selection = FreeColTestUtils.setStudentSelection(false);

    Colony colony = getSchoolColony(4, SchoolLevel.UNIVERSITY);
    assertEquals(4, colony.getUnitCount());
    Building university = colony.getBuilding(universityType);
    assertNotNull(university);
    Iterator<Unit> units = colony.getUnitIterator();

    Unit colonist = units.next();
    colonist.setType(freeColonistType);
    colonist.setLocation(colony.getBuilding(townHallType));

    Unit elder = units.next();
    assertEquals(elder.getType(), elderStatesmanType);

    elder.setLocation(university);
    assertEquals(elder.getStudent(), colonist);

    trainForTurns(colony, elder.getNeededTurnsOfTraining());
    assertEquals(elderStatesmanType, colonist.getType());

    FreeColTestUtils.setStudentSelection(selection);
  }
Beispiel #14
0
  public void testCollege() {
    Game game = ServerTestHelper.startServerGame(getTestMap(true));

    // otherwise this test will crash and burn
    boolean selection = FreeColTestUtils.setStudentSelection(false);

    Colony colony = getSchoolColony(4, SchoolLevel.COLLEGE);
    Building college = colony.getBuilding(collegeType);
    Iterator<Unit> units = colony.getUnitIterator();

    Unit colonist = units.next();
    colonist.setType(freeColonistType);
    colonist.setLocation(colony.getBuilding(townHallType));

    Unit blackSmith = units.next();
    blackSmith.setType(masterBlacksmithType);

    blackSmith.setLocation(college);
    assertEquals(blackSmith.getStudent(), colonist);

    trainForTurns(colony, blackSmith.getNeededTurnsOfTraining());
    assertEquals(masterBlacksmithType, colonist.getType());

    FreeColTestUtils.setStudentSelection(selection);
  }
Beispiel #15
0
  /** Sons of Liberty influences teaching. */
  public void testSonsOfLiberty() {
    boolean selection = FreeColTestUtils.setStudentSelection(false);
    Game game = ServerTestHelper.startServerGame(getTestMap(true));

    Colony colony = getSchoolColony(4, SchoolLevel.UNIVERSITY);
    Building university = colony.getBuilding(universityType);
    Iterator<Unit> units = colony.getUnitIterator();
    Unit colonist = units.next();
    colonist.setType(freeColonistType);
    colonist.setLocation(colony.getBuilding(townHallType));

    Unit lumberjack = units.next();
    lumberjack.setType(expertLumberJackType);
    lumberjack.setLocation(university);

    assertEquals(4, lumberjack.getNeededTurnsOfTraining());

    colony.addGoods(bellsType, 100000);
    assertEquals(2, lumberjack.getNeededTurnsOfTraining());

    trainForTurns(colony, 2);
    assertEquals(0, getUnitList(colony, freeColonistType).size());
    assertEquals(2, getUnitList(colony, expertLumberJackType).size());

    FreeColTestUtils.setStudentSelection(selection);
  }
  public void testLibertyAndImmigration() {
    Game game = ServerTestHelper.startServerGame(getTestMap(true));

    final int population = 3;
    Colony colony = getStandardColony(population);

    ServerBuilding townHall = (ServerBuilding) colony.getBuilding(townHallType);
    Unit statesman = colony.getUnitList().get(0);
    townHall.setWorkFor(statesman);
    assertEquals(bellsType, statesman.getWorkType());

    ServerBuilding church = (ServerBuilding) colony.getBuilding(chapelType);
    church.upgrade();
    Unit preacher = colony.getUnitList().get(1);
    church.setWorkFor(preacher);
    assertEquals(crossesType, preacher.getWorkType());

    assertEquals(0, colony.getGoodsCount(bellsType));
    ServerTestHelper.newTurn();

    int bells = 3;
    assertEquals(population, colony.getUnitCount());
    assertEquals(bells, colony.getNetProductionOf(bellsType));
    assertEquals(bells, colony.getGoodsCount(bellsType));

    colony.addGoods(bellsType, 7);
    bells += 7;
    assertEquals(bells, colony.getGoodsCount(bellsType));
    assertEquals(bells, colony.getLiberty());

    colony.removeGoods(bellsType, 5);
    bells -= 5;
    assertEquals(bells, colony.getGoodsCount(bellsType));
    assertEquals(bells, colony.getLiberty());

    int crosses = colony.getTotalProductionOf(crossesType) - colony.getConsumptionOf(crossesType);
    assertEquals(crosses, colony.getNetProductionOf(crossesType));
    assertEquals(crosses, colony.getGoodsCount(crossesType));
    assertEquals(crosses, colony.getImmigration());

    colony.addGoods(crossesType, 7);
    crosses += 7;
    assertEquals(crosses, colony.getGoodsCount(crossesType));
    assertEquals(crosses, colony.getImmigration());

    colony.removeGoods(crossesType, 5);
    crosses -= 5;
    assertEquals(crosses, colony.getGoodsCount(crossesType));
    assertEquals(crosses, colony.getImmigration());
  }
  /**
   * Invoked when a mouse button was pressed.
   *
   * @param e The MouseEvent that holds all the information.
   */
  @Override
  public void mousePressed(MouseEvent e) {
    if (!e.getComponent().isEnabled()) return;

    int me = e.getButton();
    if (e.isPopupTrigger()) me = MouseEvent.BUTTON3;
    Tile tile = canvas.convertToMapTile(e.getX(), e.getY());

    switch (me) {
      case MouseEvent.BUTTON1:
        // Record initial click point for purposes of dragging
        canvas.setDragPoint(e.getX(), e.getY());
        if (canvas.isGotoStarted()) {
          PathNode path = canvas.getGotoPath();
          if (path != null) {
            canvas.stopGoto();
            // Move the unit
            freeColClient
                .getInGameController()
                .goToTile(canvas.getActiveUnit(), path.getLastNode().getTile());
          }
        } else if (doubleClickTimer.isRunning()) {
          doubleClickTimer.stop();
        } else {
          centerX = e.getX();
          centerY = e.getY();
          doubleClickTimer.start();
        }
        canvas.requestFocus();
        break;
      case MouseEvent.BUTTON2:
        if (tile != null) {
          Unit unit = canvas.getActiveUnit();
          if (unit != null && unit.getTile() != tile) {
            PathNode dragPath = unit.findPath(tile);
            canvas.startGoto();
            canvas.setGotoPath(dragPath);
          }
        }
        break;
      case MouseEvent.BUTTON3:
        // Cancel goto if one is active
        if (canvas.isGotoStarted()) canvas.stopGoto();
        canvas.showTilePopup(tile, e.getX(), e.getY());
        break;
      default:
        break;
    }
  }
Beispiel #18
0
  /**
   * Handle a "attack"-message.
   *
   * @param server The <code>FreeColServer</code> handling the message.
   * @param player The <code>Player</code> the message applies to.
   * @param connection The <code>Connection</code> message was received on.
   * @return An update encapsulating the attack or an error <code>Element</code> on failure.
   */
  public Element handle(FreeColServer server, Player player, Connection connection) {
    ServerPlayer serverPlayer = server.getPlayer(connection);

    Unit unit;
    try {
      unit = serverPlayer.getOurFreeColGameObject(unitId, Unit.class);
    } catch (Exception e) {
      return DOMMessage.clientError(e.getMessage());
    }

    Tile tile;
    try {
      tile = unit.getNeighbourTile(directionString);
    } catch (Exception e) {
      return DOMMessage.clientError(e.getMessage());
    }

    MoveType moveType = unit.getMoveType(tile);
    if (moveType == MoveType.ENTER_INDIAN_SETTLEMENT_WITH_SCOUT
        || moveType == MoveType.ENTER_FOREIGN_COLONY_WITH_SCOUT
        || moveType.isAttack()) {; // OK
    } else {
      return DOMMessage.clientError(
          "Illegal attack move for: "
              + unitId
              + " type: "
              + moveType
              + " from: "
              + unit.getLocation().getId()
              + " to: "
              + tile.getId());
    }

    Unit defender = tile.getDefendingUnit(unit);
    if (defender == null) {
      return DOMMessage.clientError(
          "Could not find defender"
              + " in tile: "
              + tile.getId()
              + " from: "
              + unit.getLocation().getId());
    }

    // Proceed to attack.
    return server.getInGameController().combat(serverPlayer, unit, defender, null);
  }
 /** {@inheritDoc} */
 @Override
 public void actionPerformed(ActionEvent ae) {
   doubleClickTimer.stop();
   Tile tile = canvas.convertToMapTile(centerX, centerY);
   if (canvas.getViewMode() == GUI.MOVE_UNITS_MODE) {
     // Clear goto order when active unit is on the tile
     Unit unit = canvas.getActiveUnit();
     if (unit != null && unit.getTile() == tile) {
       freeColClient.getInGameController().clearGotoOrders(unit);
       canvas.updateCurrentPathForActiveUnit();
     } else {
       if (tile != null && tile.hasSettlement()) {
         freeColClient.getGUI().showSettlement(tile.getSettlement());
         return;
       }
     }
   }
   freeColClient.getGUI().setSelectedTile(tile);
 }
 /**
  * Why would an IndianDemandMission be invalid with the given unit and colony.
  *
  * @param aiUnit The <code>AIUnit</code> to test.
  * @param colony The <code>Colony</code> to test.
  * @return A reason why the mission would be invalid with the unit and colony or null if none
  *     found.
  */
 private static String invalidColonyReason(AIUnit aiUnit, Colony colony) {
   String reason = invalidTargetReason(colony);
   if (reason != null) return reason;
   final Unit unit = aiUnit.getUnit();
   final Player owner = unit.getOwner();
   Player targetPlayer = colony.getOwner();
   switch (owner.getStance(targetPlayer)) {
     case UNCONTACTED:
     case PEACE:
     case ALLIANCE:
       return "bad-stance";
     case WAR:
     case CEASE_FIRE:
       Tension tension = unit.getHomeIndianSettlement().getAlarm(targetPlayer);
       if (tension != null && tension.getLevel().compareTo(Tension.Level.CONTENT) <= 0)
         return "happy";
       break;
   }
   return null;
 }
 private boolean equipUnitIfPossible(UnitLabel unitLabel, AbstractGoods goods) {
   Unit unit = unitLabel.getUnit();
   if (unit.hasAbility(Ability.CAN_BE_EQUIPPED)) {
     for (EquipmentType equipment :
         freeColClient.getGame().getSpecification().getEquipmentTypeList()) {
       if (unit.canBeEquippedWith(equipment) && equipment.getGoodsRequired().size() == 1) {
         AbstractGoods requiredGoods = equipment.getGoodsRequired().get(0);
         if (requiredGoods.getType().equals(goods.getType())
             && requiredGoods.getAmount() <= goods.getAmount()) {
           int amount =
               Math.min(
                   goods.getAmount() / requiredGoods.getAmount(), equipment.getMaximumCount());
           freeColClient.getInGameController().equipUnit(unit, equipment, amount);
           unitLabel.updateIcon();
           return true;
         }
       }
     }
   }
   return false;
 }
  public void testDeathByStarvation() {
    Game game = ServerTestHelper.startServerGame(getTestMap(marsh));

    int consumption, production, unitsBeforeNewTurn = 3;
    Colony colony = getStandardColony(unitsBeforeNewTurn);
    ServerPlayer player = (ServerPlayer) colony.getOwner();

    final Building townHall = colony.getBuilding(townHallType);
    for (Unit u : colony.getUnitList()) {
      u.setLocation(townHall);
    }
    colony.removeGoods(foodGoodsType);
    colony.invalidateCache();

    consumption = colony.getFoodConsumption();
    production = colony.getFoodProduction();
    assertTrue(
        "Food consumption ("
            + consumption
            + ") should be higher than production ("
            + production
            + ")",
        consumption > production);
    assertEquals("No food stored in colony", 0, colony.getGoodsCount(foodType));
    assertEquals("Wrong number of units in colony", unitsBeforeNewTurn, colony.getUnitCount());

    ServerTestHelper.newTurn();

    consumption = colony.getFoodConsumption();
    production = colony.getFoodProduction();
    assertTrue(
        "Food consumption ("
            + consumption
            + ") should be higher than production ("
            + production
            + ")",
        consumption > production);
    assertEquals("No food stored in colony", 0, colony.getGoodsCount(foodType));
    assertEquals("Wrong number of units in colony", unitsBeforeNewTurn - 1, colony.getUnitCount());
  }
Beispiel #23
0
 /** Creates a colony with a university and n elder statesmen */
 private Colony getSchoolColony(int n, SchoolLevel slevel) {
   Colony colony = getStandardColony(n);
   for (Unit u : colony.getUnitList()) u.setType(elderStatesmanType);
   BuildingType type = null;
   switch (slevel) {
     case SCHOOLHOUSE:
       type = schoolType;
       break;
     case COLLEGE:
       type = collegeType;
       break;
     case UNIVERSITY:
       type = universityType;
       break;
     default:
       fail("Setup error, cannot setup school");
   }
   Building school = new ServerBuilding(colony.getGame(), colony, type);
   colony.addBuilding(school);
   assertEquals(school.getUnitList().size(), 0);
   colony.addGoods(grainType, 150); // prevent starving during tests
   return colony;
 }
  public void testEqualFoodProductionConsumptionCase() {
    Game game = ServerTestHelper.startServerGame(getTestMap(desert));

    // Setting test colony
    Tile colonyTile = game.getMap().getTile(5, 8);
    Colony colony =
        FreeColTestUtils.getColonyBuilder().colonyTile(colonyTile).initialColonists(1).build();

    // Set the food production of the center tile of the colony to 2
    // This will be the only food production of the colony
    List<AbstractGoods> colonyTileProduction = colonyTile.getType().getPossibleProduction(true);
    for (int i = 0; i < colonyTileProduction.size(); i++) {
      AbstractGoods production = colonyTileProduction.get(i);
      if (production.getType() == foodGoodsType) {
        production.setAmount(2);
        break;
      }
    }
    Unit unit = colony.getUnitList().get(0);
    unit.setLocation(colony.getWorkLocationFor(unit, bellsType));

    // Verify that there is enough food stored
    colony.addGoods(foodGoodsType, colony.getFoodConsumption() * 2);

    assertEquals(
        "Production not equal to consumption",
        colony.getFoodConsumption(),
        colony.getFoodProduction());

    int colonists = colony.getUnitCount();
    assertEquals("Unexpected change of colonists in colony", colonists, colony.getUnitCount());

    assertEquals(
        "Unexpected change of production/consumption ratio",
        colony.getFoodProduction(),
        colony.getFoodConsumption());
  }
Beispiel #25
0
  public void testColonialRegular() {
    boolean selection = FreeColTestUtils.setStudentSelection(false);
    Game game = ServerTestHelper.startServerGame(getTestMap(true));

    Colony colony = getSchoolColony(4, SchoolLevel.UNIVERSITY);
    Building university = colony.getBuilding(universityType);
    colony.getOwner().addAbility(new Ability(Ability.INDEPENDENCE_DECLARED));
    Iterator<Unit> units = colony.getUnitIterator();

    Unit regular = units.next();
    regular.setType(colonialRegularType);

    Unit colonist = units.next();
    colonist.setType(freeColonistType);
    colonist.setLocation(colony.getBuilding(townHallType));

    regular.setLocation(university);
    assertEquals(colonist, regular.getStudent());
    trainForTurns(colony, freeColonistType.getEducationTurns(veteranSoldierType));

    assertEquals(veteranSoldierType, colonist.getType());

    FreeColTestUtils.setStudentSelection(selection);
  }
  /**
   * Find a suitable cash in location for this unit.
   *
   * @param aiUnit The <code>AIUnit</code> to execute this mission.
   * @param range The maximum number of moves to search.
   * @param deferOK Enables deferring to a fallback colony.
   * @return A <code>PathNode</code> to the target, or null if not found which includes the case
   *     when Europe should be preferred (because the unit can not get there by itself).
   */
  private static PathNode findTargetPath(AIUnit aiUnit, int range, boolean deferOK) {
    if (invalidAIUnitReason(aiUnit) != null) return null;
    final Unit unit = aiUnit.getUnit();
    final Location start = unit.getPathStartLocation();
    final Player player = unit.getOwner();
    final Europe europe = player.getEurope();
    final Unit carrier = unit.getCarrier();
    final CostDecider standardCd = CostDeciders.avoidSettlementsAndBlockingUnits();
    PathNode path;

    if (player.getNumberOfSettlements() <= 0 || start == null) {
      // No settlements or not on the map, so go straight to
      // Europe.  If Europe does not exist then this mission is
      // doomed.
      return (europe == null)
          ? null
          : unit.findPath(unit.getLocation(), europe, carrier, standardCd);
    }

    // Can the unit get to a cash in site?
    return unit.search(start, getGoalDecider(aiUnit, deferOK), standardCd, range, carrier);
  }
Beispiel #27
0
  /**
   * Create a new <code>AttackMessage</code> for the supplied unit and direction.
   *
   * @param unit The <code>Unit</code> attacking.
   * @param direction The <code>Direction</code> to attack in.
   */
  public AttackMessage(Unit unit, Direction direction) {
    super(getXMLElementTagName());

    this.unitId = unit.getId();
    this.directionString = String.valueOf(direction);
  }
Beispiel #28
0
 /**
  * Create a new <code>BuildColonyMessage</code> with the supplied name and building unit.
  *
  * @param colonyName The name for the new colony.
  * @param builder The <code>Unit</code> to do the building.
  */
 public BuildColonyMessage(String colonyName, Unit builder) {
   this.colonyName = colonyName;
   this.builderId = builder.getId();
 }
Beispiel #29
0
  /** The constructor that will add the items to this panel. */
  public ReportLabourPanel(FreeColClient freeColClient) {
    super(freeColClient, "reportLabourAction");

    this.data = new HashMap<>();
    this.unitCount = new TypeCountMap<>();
    for (Unit unit : getMyPlayer().getUnits()) {
      UnitType type = unit.getType();
      this.unitCount.incrementCount(type, 1);
      Map<Location, Integer> unitMap = this.data.get(type);
      if (unitMap == null) {
        unitMap = new HashMap<>();
        this.data.put(type, unitMap);
      }

      Location location = unit.getLocation();
      if (location == null) {
        logger.warning("Unit has null location: " + unit);
      } else if (location.getSettlement() != null) {
        location = location.getSettlement();
      } else if (unit.isInEurope()) {
        location = getMyPlayer().getEurope();
      } else if (location.getTile() != null) {
        location = location.getTile();
      }
      Integer count = unitMap.get(location);
      if (count == null) {
        unitMap.put(location, 1);
      } else {
        unitMap.put(location, count + 1);
      }
    }

    this.colonies = freeColClient.getMySortedColonies();

    DefaultListModel<LabourUnitPanel> model = new DefaultListModel<>();
    for (UnitType unitType : getSpecification().getUnitTypeList()) {
      if (unitType.isPerson() && unitType.isAvailableTo(getMyPlayer())) {
        int count = this.unitCount.getCount(unitType);
        model.addElement(new LabourUnitPanel(unitType, count));
      }
    }
    Action selectAction =
        new AbstractAction() {
          @Override
          public void actionPerformed(ActionEvent e) {
            showDetails();
          }
        };
    Action quitAction =
        new AbstractAction() {
          @Override
          public void actionPerformed(ActionEvent e) {
            getGUI().removeFromCanvas(ReportLabourPanel.this);
          }
        };

    // Add all the components
    this.panelList = new JList<>(model);
    this.panelList.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "select");
    this.panelList.getActionMap().put("select", selectAction);
    this.panelList.getInputMap().put(KeyStroke.getKeyStroke("ESCAPE"), "quit");
    this.panelList.getActionMap().put("quit", quitAction);
    this.panelList.addMouseListener(
        new MouseAdapter() {
          @Override
          public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() == 2) {
              showDetails();
            }
          }
        });
    this.panelList.setOpaque(false);
    this.panelList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    this.panelList.setLayoutOrientation(JList.HORIZONTAL_WRAP);
    this.panelList.setVisibleRowCount(-1);
    this.panelList.setCellRenderer(new LabourUnitPanelRenderer());

    this.scrollPane.setViewportView(this.panelList);
  }
  /** {@inheritDoc} */
  @Override
  public Mission doMission(LogBuilder lb) {
    lb.add(tag);
    String reason = invalidReason();
    if (reason != null) return lbFail(lb, false, reason);

    final AIUnit aiUnit = getAIUnit();
    final Unit unit = getUnit();
    final IndianSettlement is = unit.getHomeIndianSettlement();
    Direction d;

    while (!this.demanded) {
      Unit.MoveType mt = travelToTarget(getTarget(), null, lb);
      switch (mt) {
        case MOVE_HIGH_SEAS:
        case MOVE_NO_MOVES:
        case MOVE_ILLEGAL:
          return lbWait(lb);

        case MOVE_NO_REPAIR:
          return lbFail(lb, false, AIUNITDIED);

        case MOVE_NO_TILE:
          return this;

        case ATTACK_SETTLEMENT: // Arrived?
          d = unit.getTile().getDirection(getTarget().getTile());
          if (d != null) break; // Yes, arrived at target
          // Fall through
        case ATTACK_UNIT: // Something is blocking our path
          Location blocker = resolveBlockage(aiUnit, getTarget());
          if (blocker == null) {
            moveRandomly(tag, null);
            continue;
          }
          d = unit.getTile().getDirection(blocker.getTile());
          if (AIMessage.askAttack(aiUnit, d)) {
            return lbAttack(lb, blocker);
          }
          continue;

        default:
          return lbMove(lb, mt);
      }

      // Load the goods.
      lbAt(lb);
      Colony colony = (Colony) getTarget();
      Player enemy = colony.getOwner();
      Goods goods = selectGoods(colony);
      GoodsType type = (goods == null) ? null : goods.getType();
      int amount = (goods == null) ? 0 : goods.getAmount();
      if (goods == null) {
        if (!enemy.checkGold(1)) {
          return lbDone(lb, false, "empty handed");
        }
        amount = enemy.getGold() / 20;
        if (amount == 0) amount = enemy.getGold();
      }
      this.demanded = AIMessage.askIndianDemand(aiUnit, colony, type, amount);
      if (this.demanded && (goods == null || hasTribute())) {
        if (goods == null) {
          return lbDone(lb, false, "accepted tribute ", amount, " gold");
        }
        lb.add(", accepted tribute ", goods);
        return lbRetarget(lb);
      }

      // Consider attacking if not content.
      int unitTension = (is == null) ? 0 : is.getAlarm(enemy).getValue();
      int tension = Math.max(unitTension, unit.getOwner().getTension(enemy).getValue());
      d = unit.getTile().getDirection(colony.getTile());
      if (tension >= Tension.Level.CONTENT.getLimit() && d != null) {
        if (AIMessage.askAttack(aiUnit, d)) lbAttack(lb, colony);
      }
      return lbDone(lb, false, "refused at ", colony);
    }

    // Take the goods home
    for (; ; ) {
      Unit.MoveType mt =
          travelToTarget(getTarget(), CostDeciders.avoidSettlementsAndBlockingUnits(), lb);
      switch (mt) {
        case MOVE: // Arrived
          break;

        case MOVE_HIGH_SEAS:
        case MOVE_NO_MOVES:
        case MOVE_ILLEGAL:
          return lbWait(lb);

        case MOVE_NO_REPAIR:
          return lbFail(lb, false, AIUNITDIED);

        case MOVE_NO_TILE:
          return this;

        default:
          return lbMove(lb, mt);
      }

      // Unload the goods
      lbAt(lb);
      GoodsContainer container = unit.getGoodsContainer();
      for (Goods goods : container.getCompactGoods()) {
        Goods tribute = container.removeGoods(goods.getType());
        is.addGoods(tribute);
      }
      return lbDone(lb, false, "unloaded tribute");
    }
  }