Package net.sf.freecol.common.model
Class Unit
- java.lang.Object
-
- All Implemented Interfaces:
java.lang.Comparable<FreeColObject>,Consumer,Locatable,Location,Movable,Nameable,Ownable,ObjectWithId
- Direct Known Subclasses:
ServerUnit
public class Unit extends GoodsLocation implements Consumer, Locatable, Movable, Nameable, Ownable
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description private static classUnit.ClosestSettlementGoalDeciderstatic classUnit.MoveTypeA move type.private static classUnit.PortModeInternal state for findIntermediatePort.static classUnit.UnitLabelTypeWhat type of unit label do we want?static classUnit.UnitStateA state a Unit can have.-
Nested classes/interfaces inherited from class net.sf.freecol.common.model.UnitLocation
UnitLocation.NoAddReason
-
-
Field Summary
Fields Modifier and Type Field Description protected intattritionThe attrition this unit has accumulated.private static java.lang.StringATTRITION_TAGstatic java.lang.StringCARGO_CHANGEprivate static java.lang.StringCOUNT_TAGprivate static java.lang.StringCURRENT_STOP_TAGprotected intcurrentStopWhich stop in a trade route the unit is going to.static java.util.Comparator<Unit>decreasingSkillComparatorA comparator to compare units by decreasing skill level.static intDEFAULT_UNIT_VALUEDefault value of unpriced units, used in evaluate_for.protected LocationdestinationA destination for go-to moves.private static java.lang.StringDESTINATION_TAGprivate static java.lang.StringENTRY_LOCATION_TAGprotected LocationentryLocationThe last entry location used by this unit.protected java.lang.StringethnicityThe original ethnicity.private static java.lang.StringETHNICITY_TAGprotected intexperienceThe mount of experience a unit has earned.private static java.lang.StringEXPERIENCE_TAGprivate static java.lang.StringEXPERIENCE_TYPE_TAGprotected GoodsTypeexperienceTypeWhat type of goods this unit last earned experience producing.private static java.lang.StringHIT_POINTS_TAGprotected inthitPointsFor now; only used by ships when repairing.static java.util.Comparator<Unit>increasingSkillComparatorA comparator to compare units by increasing skill level.private static java.lang.StringINDIAN_SETTLEMENT_TAGprotected IndianSettlementindianSettlementThe home settlement of a native unit.protected LocationlocationThe current unit location.private static java.lang.StringLOCATION_TAGstatic java.util.Comparator<Unit>locComparatorCompare units by location.private static java.util.logging.Loggerloggerstatic intMANY_TURNSA large number of turns, denoting pathfinding failure.static java.lang.StringMOVE_CHANGEprivate static java.lang.StringMOVES_LEFT_TAGprotected intmovesLeftThe number of moves this unit has left this turn.protected java.lang.StringnameThe individual name of this unit, not of the unit type.private static java.lang.StringNAME_TAGprotected java.lang.StringnationalityThe original nationality.private static java.lang.StringNATIONALITY_TAGprivate static java.lang.StringOLD_EQUIPMENT_TAGprivate static java.lang.StringOLD_TILE_IMPROVEMENT_TAGprotected PlayerownerThe owner player.private static java.lang.StringOWNER_TAGprotected RoleroleCurrent unit role.static java.lang.StringROLE_CHANGEprivate static java.lang.StringROLE_COUNT_TAGprivate static java.lang.StringROLE_TAGprotected introleCountThe amount of role-equipment this unit carries, subject to role.getMaximumCount().static java.util.function.Predicate<Unit>sentryPredUseful predicate for finding sentried land units.private static java.util.Comparator<Settlement>settlementStartComparatorComparator to rank settlements by accessibility by sea to Europe.protected Unit.UnitStatestateCurrent unit state.private static java.lang.StringSTATE_TAGprotected UnitstudentThe student of this Unit, if it has one.private static java.lang.StringSTUDENT_TAGstatic java.lang.StringTAGprotected UnitteacherThe teacher of this Unit, if it has one.private static java.lang.StringTEACHER_TAGprivate static java.lang.StringTRADE_ROUTE_TAGprotected TradeRoutetradeRouteThe trade route this unit has.private static java.lang.StringTREASURE_AMOUNT_TAGprotected inttreasureAmountTo be used only for type == TREASURE_TRAINprivate static java.lang.StringTURNS_OF_TRAINING_TAGprotected intturnsOfTrainingNumber of turns of training needed by this unit.protected UnitTypetypeThe unit type.static java.util.Comparator<Unit>typeRoleComparatorA comparator to compare units by type, then role index, then the FCO order.private static intUNIT_CLASS_INDEXClass index for units.private static java.lang.StringUNIT_TYPE_TAGprivate static java.lang.StringVISIBLE_GOODS_COUNT_TAGprotected intvisibleGoodsCountThe amount of goods carried by this unit.private static java.lang.StringWORK_LEFT_TAGprivate static java.lang.StringWORK_TYPE_TAGprotected TileImprovementworkImprovementWhat is being improved (to be used only for PIONEERs - where they are working.protected intworkLeftThe number of turns until the work is finished (e.g.protected GoodsTypeworkTypeWhat type of goods this unit produces in its occupation.-
Fields inherited from class net.sf.freecol.common.model.FreeColGameObject
initialized
-
Fields inherited from class net.sf.freecol.common.model.FreeColObject
ARRAY_SIZE_TAG, DEFAULT_CLASS_INDEX, fcoComparator, ID_ATTRIBUTE_TAG, PARTIAL_ATTRIBUTE_TAG, VALUE_TAG
-
Fields inherited from interface net.sf.freecol.common.model.Consumer
BUILDING_PRIORITY, COLONY_PRIORITY, COMPARATOR, POPULATION_PRIORITY, UNIT_PRIORITY
-
Fields inherited from interface net.sf.freecol.common.model.Location
LOCATION_RANK_EUROPE, LOCATION_RANK_HIGHSEAS, LOCATION_RANK_NOWHERE
-
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description booleanadd(Locatable locatable)Adds aLocatableto this Location.voidaddFeature(Feature feature)Adds a feature to the Unit.private booleanallowContact(Settlement settlement)Is this unit allowed to contact a settlement?private booleanallowMoveFrom(Tile from)Is this unit allowed to move from a source tile? Implements the restrictions on moving from water.booleanatStop(TradeRouteStop stop)Convenience function to check if a unit is at a stop.static booleanbetterDefender(Unit defender, double defenderPower, Unit other, double otherPower)Is an alternate unit a better defender than the current choice.booleancanAmbush(Unit defender)Can this unit ambush another?booleancanAttack(Unit defender)Can this unit attack a specified defender? A naval unit can never attack a land unit or settlement, but a land unit *can* attack a naval unit if it is beached.booleancanBeStudent(Unit teacher)Can this unit be a student of a teacher unit?booleancanBuildColony()Check if this unit can build a colony.RolecanCaptureEquipment(Role role)After winning a battle, can this unit capture the loser's role equipment?booleancanCaptureGoods()Can this unit capture enemy goods?booleancanCarryGoods()Can this unit carry goods.booleancanCarryTreasure()Can this unit carry treasure (like a treasure train)?booleancanCarryUnits()Can this unit carry other units?booleancanCashInTreasureTrain()Checks if the treasure train can be cashed in at it's currentLocation.booleancanCashInTreasureTrain(Location loc)Checks if the treasure train can be cashed in at the givenLocation.booleancanMoveToHighSeas()Checks if thisUnitcan be moved to the high seas from its current location.voidchangeExperienceType(GoodsType type)Sets the type of goods this unit has accrued experience producing.IndianSettlementchangeHomeIndianSettlement(IndianSettlement indianSettlement)Changes the homeIndianSettlementfor this unit.voidchangeOwner(Player owner)Change the owner of this unit.voidchangeRole(Role role, int roleCount)Change the current role of this unit.booleanchangeRoleCount(int delta)Change the current role count.booleanchangeType(UnitType unitType)Changes the type of the unit.voidchangeWorkType(GoodsType type)Change the type of goods this unit is producing in its current occupation.Constants.IntegrityTypecheckIntegrity(boolean fix, LogBuilder lb)Checks the integrity of this game object.booleancheckSetState(Unit.UnitState s)Checks if aUnitcan get the given state set.<T extends FreeColObject>
booleancopyIn(T other)Copy another FreeColObject into this one if it is compatible.booleancouldCarry(Goods g)Could this unit carry some specified goods? This ignores the current load.booleancouldCarry(Unit u)Could this unit carry a specified one? This ignores the current load.booleancouldMove()Is this unit a suitable `next active unit', that is, the unit needs to be currently movable by the player.voiddamageShip(Location repair)Damage this unit (which should be a ship).voiddisposeResources()Dispose of the resources of this object, and finally remove it from the game.intevaluateFor(Player player)Evaluate this unit for trade purposes.PathNodefindIntermediatePort(Location dst)Find a path to a settlement nearer to a destination.PathNodefindOurNearestOtherSettlement()Find a path for this unit to the nearest settlement with the same owner that is reachable without a carrier, excepting any on the current tile.PathNodefindOurNearestPort()Find a path for this unit to the nearest settlement with the same owner that is reachable without a carrier and is connected to Europe by sea, or Europe if it is closer.PathNodefindOurNearestSettlement()Find a path for this unit to the nearest settlement with the same owner that is reachable without a carrier.PathNodefindOurNearestSettlement(boolean excludeStart, int range, boolean coastal)Find a path for this unit to the nearest settlement with the same owner that is reachable without a carrier.PathNodefindOurNearestSettlement(Tile startTile, boolean excludeStart, int range, boolean coastal)Find a path for this unit to the nearest settlement with the same owner that is reachable without a carrier.PathNodefindPath(Location end)Finds the fastest path from the current location to the specified one.PathNodefindPath(Location start, Location end)Finds the fastest path from a given location to a specified one.PathNodefindPath(Location start, Location end, Unit carrier)Finds the fastest path from a given location to a specified one, with an optional carrier.PathNodefindPath(Location start, Location end, Unit carrier, CostDecider costDecider, LogBuilder lb)Finds a quickest path between specified locations, optionally using a carrier and special purpose cost decider.PathNodefindPathToNeighbour(Location start, Tile end, Unit carrier, CostDecider costDecider)Finds a quickest path to a neighbouring tile to a specified target tile, optionally using a carrier and special purpose cost decider.booleanfollowingTradeRoute()Is this unit available to move along a trade route? Used as a predicate in Player.nextTradeRouteUnitIterator.java.util.stream.Stream<Ability>getAbilities(java.lang.String id, FreeColSpecObjectType fcgot, Turn turn)Gets the set of abilities with the given identifier from this object.<T extends Settlement>
TgetAdjacentSettlement(java.lang.String settlementId, java.lang.Class<T> returnClass)Get a settlement by identifier, validating as much as possible.StringTemplategetApparentOwnerName()Get the name of the apparent owner of this Unit, (like getOwner().getNationAsString() but handles pirates).intgetAttrition()Gets the attrition of this unit.RolegetAutomaticRole()Gets a role that can be equipped automatically assumed in case of an attack.java.util.stream.Stream<Role>getAvailableRoles(java.util.List<Role> roles)Filter a list of roles to return only those available to this unit, returning a stream.java.util.List<Role>getAvailableRolesList(java.util.List<Role> roles)Filter a list of roles to return only those available to this unit.TilegetBestEntryTile(Tile tile)Gets the best (closest) entry location for this unit to reach a given tile.floatgetBurnProbability()Gets the probability that an attack by this unit will provoke natives to burn our missions.intgetCargoCapacity()Gets the total space this unit has to carry cargo.intgetCargoSpaceTaken()Gets the space occupied by cargo in this unit (both goods and units).UnitgetCarriedUnitById(java.lang.String id)Get a carried unit by identifier.UnitgetCarrier()Gets the carrier this unit is aboard if any.intgetClassIndex()Accessor for the class index.ColonygetClosestColony(java.util.List<Colony> colonies)Get the colony that can be reached by this unit in the least number of turns.ColonygetClosestColony(java.util.stream.Stream<Colony> colonies)Get the colony that can be reached by this unit in the least number of turns.StringTemplategetCombatLabel(Tile tile)Get a label for the chance of success in a potential combat.java.util.Set<Modifier>getCombatModifiers(java.lang.String id, FreeColSpecObjectType fcgot, Turn turn)Get modifiers required for combat.java.util.List<Goods>getCompactGoodsList()Get a compact version of the goods carried by this unit.java.util.List<AbstractGoods>getConsumedGoods()Returns a list of GoodsTypes this Consumer consumes.java.util.stream.Stream<Modifier>getConsumptionModifiers(java.lang.String id)Get the modifier set with the given id.floatgetConvertProbability()Gets the probability that an attack by this unit will provoke a native to convert.intgetCurrentStop()Get the current trade route stop.java.util.List<TradeRouteStop>getCurrentStops()Get the stop the unit is heading for or at.java.lang.StringgetDescription()Get the basic i18n description for this unit.java.lang.StringgetDescription(Unit.UnitLabelType ult)Get the basic i18n description for this unit.LocationgetDestination()Get the destination of this unit.StringTemplategetDestinationLabel()Get a destination label for this unit.FreeColObjectgetDisplayObject()Get an object to display when showing the user messages for this object.LocationgetEntryLocation()Gets the entry location for this unit to use when returning fromEurope.java.lang.StringgetEthnicity()Gets the ethnicity of this Unit.intgetExperience()Gets the experience of thisUnitat its current experienceType.GoodsTypegetExperienceType()Gets the type of goods this unit has accrued experience producing.TilegetFullEntryLocation()Gets the entry tile for this unit, or if null the default entry location for the owning player.intgetGoodsCapacity()Gets the maximum number ofGoodsthis Location can hold.java.util.List<AbstractGoods>getGoodsDifference(Role role, int roleCount)Get the change in goods required to change to a new role/count.private java.util.List<Goods>getGoodsInternal(boolean compact)Get the goods carried by this unit.java.util.List<Goods>getGoodsList()Get the goods carried by this unit.intgetGoodsSpaceTaken()Gets the space occupied by goods in this unit.intgetHitPoints()Gets the unit hit points.IndianSettlementgetHomeIndianSettlement()Gets theIndianSettlementhome for this unit.intgetInitialMovesLeft()Gets the amount of moves this unit has at the beginning of each turn.StringTemplategetLabel()Get a plain string template for a unit.StringTemplategetLabel(Unit.UnitLabelType ult)Get a string template for a unit.private Unit.MoveTypegetLandMoveType(Tile from, Tile target)Gets the type of a move that is made when moving a land unit to from one tile to another.private Unit.MoveTypegetLearnMoveType(Tile from, Settlement settlement)Get theMoveTypewhen moving a colonist to a settlement.intgetLineOfSight()Gets the line of sight of thisUnit.FreeColGameObjectgetLinkTarget(Player player)Get a suitable game object to use as a clickable link in messages to a player.intgetLoadableAmount(GoodsType type)Gets the extra amount of a specified type of goods that could be loaded onto this unit.LocationgetLocation()Gets the location of this unit.private java.util.stream.Stream<Ability>getLocationAbilities(java.lang.String id, Turn turn)Get abilities specific to this location.StringTemplategetLocationLabel()Get a label for this location.RolegetMilitaryRole()Get a military role for this unit.private Unit.MoveTypegetMissionaryMoveType(Tile from, Settlement settlement)Get theMoveTypewhen moving a missionary to a settlement.java.util.Set<Modifier>getMissionaryTradeModifiers(boolean sense)Gets the appropriate trade bonuses due to a missionary unit.java.util.stream.Stream<Modifier>getModifiers(java.lang.String id, FreeColSpecObjectType fcgot, Turn turn)Gets the set of modifiers with the given identifier from this object.intgetMoveCost(Tile target)Gets the cost of moving thisUnitonto the givenTile.intgetMoveCost(Tile from, Tile target, int ml)Gets the cost of moving thisUnitfrom the givenTileonto the givenTile.java.lang.StringgetMovesAsString()Make a label showing the unit moves left.intgetMovesLeft()Get the moves left this turn.Unit.MoveTypegetMoveType(Direction direction)Gets the type of a move made in a specified direction.Unit.MoveTypegetMoveType(Tile target)Gets the type of a move that is made when moving from one tile to another.Unit.MoveTypegetMoveType(Tile from, Tile target, int ml)Gets the type of a move that is made when moving from one tile to another.java.lang.StringgetName()Get the individual name of this unit.java.lang.StringgetNationality()Gets the nationality of this Unit.private Unit.MoveTypegetNavalMoveType(Tile from, Tile target)Gets the type of a move that is made when moving a naval unit from one tile to another.intgetNeededTurnsOfTraining()Gets the number of turns this unit has to train to educate a student.TilegetNeighbourTile(java.lang.String directionString)Gets the tile in a given direction.UnitLocation.NoAddReasongetNoAddReason(Locatable locatable)Gets the reason why a givenLocatablecan not be added to this Location.StringTemplategetOccupationLabel(Player player, boolean full)Get a label for the current unit occupation.PlayergetOwner()Gets the owner of thisOwnable.private java.util.Comparator<Tile>getPathComparator(Location start, Unit carrier, CostDecider costDecider)Get a comparator to rank locations by proximity to a start location, using this unit+optional carrier and cost decider.LocationgetPathStartLocation()Gets a suitable location to start path searches for a unit.intgetPioneerScore()Score this unit with its suitability for pioneering.intgetPriority()The priority of this Consumer.ProductionInfogetProductionInfo(java.util.List<AbstractGoods> input)Gets theProductionInfofor this unit.intgetRank()Get a integer for this location, for the benefit of location comparators.StringTemplategetRepairLabel()Get a string template describing the repair state of this unit.LocationgetRepairLocation()Finds the closestLocationto this tile where this ship can be repaired, excluding the current colony.RolegetRole()Gets the unit role.intgetRoleCount()Get the role count.java.lang.StringgetRoleSuffix()Get the last part of the role identifier, which is often used as part of a message key.intgetSailTurns()Gets the number of turns this unit will need to sail to/from Europe.intgetScoreValue()Score this unit.intgetScoutScore()Score this unit with its suitability for scouting.SettlementgetSettlement()Gets theSettlementthisLocationis located in.Unit.MoveTypegetSimpleMoveType(Direction direction)Gets the type of a move made in a specified direction, without checking if the unit has moves left or logging errors.Unit.MoveTypegetSimpleMoveType(Tile target)Gets the type of a move that is made when moving from one tile to another, without checking if the unit has moves left or logging errors.Unit.MoveTypegetSimpleMoveType(Tile from, Tile target)Gets the type of a move that is made when moving from one tile to another, without checking if the unit has moves left or logging errors.intgetSkillLevel()Gets the skill level.intgetSpaceLeft()Gets the number of free cargo slots left on this unit.intgetSpaceTaken()Gets the current space taken by the units in this location.Unit.UnitStategetState()Gets the state of thisUnit.TradeRouteStopgetStop()Get the stop the unit is heading for or at.UnitgetStudent()Get the unit being taught.UnitgetTeacher()Get the unit teaching this one.UnitTypegetTeachingType(Unit teacher)Get the skill another unit can teach this unit.UnitTypegetTeachingType(UnitType teacherType)Get the skill another unit type can teach this unit.TilegetTile()Gets the Tile associated with this Location.TradeLocationgetTradeLocation()Get the current trade location.private Unit.MoveTypegetTradeMoveType(Settlement settlement)Get theMoveTypewhen moving a trading unit to a settlement.TradeRoutegetTradeRoute()Get the unit trade route, if any.intgetTransportFee()Get the fee that would have to be paid to transport this treasure to Europe.intgetTreasureAmount()Get the current amount of treasure in this unit.PathNodegetTrivialPath()Gets the trivial path for this unit.intgetTurnsForRepair()Get how many turns left to be repairedintgetTurnsOfTraining()Gets the number of turns this unit has been training.intgetTurnsToReach(Location end)Gets the number of turns required for this unit to reach a destination location from its current position.intgetTurnsToReach(Location start, Location end)Gets the number of turns required for this unit to reach a destination location from a starting location.intgetTurnsToReach(Location start, Location end, Unit carrier, CostDecider costDecider)Gets the number of turns required for this unit to reach a destination location from a starting location, using an optional carrier and cost decider.UnitTypegetType()Get theUnitTypevalue.UnitTypeChangegetUnitChange(java.lang.String change)Get a unit change for this unit.UnitTypeChangegetUnitChange(java.lang.String change, UnitType toType)Get a unit change for this unit.UnitTypeChangegetUnitChange(java.lang.String change, UnitType toType, Player player)Get a unit change for this unit, including the ownership check.static StringTemplategetUnitDestinationLabel(java.lang.String tag, Location destination, Player player)Get a destination label for a given unit tag, destination and player.static intgetUnitSkillLevel(UnitType unitType)Gets the skill level of the given type ofUnit.intgetUnitSpaceTaken()Gets the space occupied by units in this unit.intgetVisibleGoodsCount()Get the visible amount of goods that is carried by this unit.java.util.Set<Tile>getVisibleTileSet()Get the tiles visible to this unit.TileImprovementgetWorkImprovement()Gets the TileImprovement that this pioneer is contributing to.intgetWorkLeft()Gets the amount of work left.WorkLocationgetWorkLocation()Gets the work location this unit is working in.TilegetWorkTile()Get the work tile this unit is working in, if any.intgetWorkTurnsLeft()Get the number of turns of work left.GoodsTypegetWorkType()Gets the type of goods this unit is producing in its current occupation.java.lang.StringgetXMLTagName()Get the serialization tag for this object.booleangoingToDestination()Is this unit a suitable `going-to unit', that is, the unit needs have a valid destination and be able to progress towards it.booleanhasCargo()Is this unit carrying any cargo (goods or unit).booleanhasDefaultRole()Does this unit have the default role?booleanhasGoodsCargo()Is this unit carrying any goods cargo?booleanhasNativeEthnicity()Identifies whether this unit came from a native tribe.booleanhasSpaceLeft()Is there free space left on this unit?booleanhasTile()Is this unit on a tile?private voidinitialize()Initialize the nationality and ethnicity.voidinvalidateCache()Invalidate any cache dependent on the goods levels.booleanisArmed()Does the unit have arms?booleanisAtLocation(Location loc)Is this unit at a specified location?booleanisAtSea()Checks whether thisUnitis at sea off the map, or on board of a carrier that is.booleanisBeached()Is the unit a beached ship?booleanisBeached(Tile tile)Would this unit be beached if it was on a particular tile?booleanisCarrier()Checks if thisUnitis able to carryLocatables.booleanisColonist()Checks if thisUnitis a `colonist'.booleanisDamaged()Checks if this unit is under repair.booleanisDefensiveUnit()Checks if this is an defensive unit.booleanisInColony()Checks whether this unit is working inside a colony.booleanisInDanger(int range, float threat)Checks if there is a credible threatening unit to this unit within a range of moves.booleanisInEurope()Checks if thisUnitis located in Europe.booleanisInMission()Checks if this unit is running a mission.booleanisMounted()Does the unit have a mount?booleanisNaval()Checks if thisUnitis naval.booleanisOffensiveUnit()Checks if this is an offensive unit.booleanisOnCarrier()Verifies if the unit is aboard a carrierbooleanisOnTile()Is this unit on a tile?booleanisOwnerHidden()Is this a unit that hides its ownership?booleanisPerson()Checks if this unit is a person, that is not a ship or wagon.booleanisReadyToTrade()Is this unit ready to operate a trade route?booleanisTileAccessible(Tile tile)Does a basic check whether a unit can ever expect to move to a tile.booleanisTradingUnit()Checks if this is a tradingUnit, meaning that it can trade with settlements.booleanisUndead()Checks if this unit is an undead.booleanlosingEquipmentDemotesUnit()Does losing equipment mean the demotion of this unit?booleanlosingEquipmentKillsUnit()Does losing a piece of equipment mean the death of this unit?voidmodifyExperience(int value)Modifies the experience of thisUnitat its current experienceType.private booleannonExpertWorker(GoodsType work)Is this unit a person that is making a given goods type, but not an expert at it.protected voidreadAttributes(FreeColXMLReader xr)Reads the attributes of this object from an XML stream.protected voidreadChild(FreeColXMLReader xr)Reads a single child object.protected voidreadChildren(FreeColXMLReader xr)Reads the children of this object from an XML stream.private booleanreadyAndAble()Basic checks for whether a unit is usable ATM.private LocationrealStart(Location start, Unit carrier)Unified argument tests for full path searches, which then finds the actual starting location for the path.UnitreduceVisibility(Tile tile, Player player)Copy the unit, reduce visibility into any carrier and reference to a settlement.booleanremove(Locatable locatable)Removes aLocatablefrom this Location.LocationresolveDestination()Resolves a destination for a unit on the high seas.booleanroleIsAvailable(Role role)Is a role available to this unit?PathNodesearch(Location start, GoalDecider gd, CostDecider cd, int maxTurns, Unit carrier)Convenience wrapper for theMap.search(net.sf.freecol.common.model.Unit, net.sf.freecol.common.model.Location, net.sf.freecol.common.model.pathfinding.GoalDecider, net.sf.freecol.common.model.pathfinding.CostDecider, int, net.sf.freecol.common.model.Unit, net.sf.freecol.common.util.LogBuilder)function.PathNodesearchForDanger(int range, float threat)Searches for a unit that is a credible threatening unit to this unit within a range.voidsetAttrition(int attrition)Sets the attrition of this unit.voidsetCurrentStop(int currentStop)Set the current stop.voidsetDestination(Location newDestination)Sets the destination of this unit.voidsetEntryLocation(Location entryLocation)Sets the entry location in which this unit will be put when returning fromEurope.voidsetEthnicity(java.lang.String newEthnicity)Sets the ethnicity of this Unit.voidsetExperience(int experience)Sets the experience of thisUnitat its current experienceType.voidsetHitPoints(int hitPoints)Sets the hit points for this unit.voidsetHomeIndianSettlement(IndianSettlement indianSettlement)Sets the homeIndianSettlementfor this unit.booleansetLocation(Location newLocation)Sets the location of this unit.voidsetLocationNoUpdate(Location newLocation)Sets the units location without updating any other variables get/setLocation are in Locatable interface.voidsetMovesLeft(int moves)Sets the moves left this turn.voidsetName(java.lang.String newName)Set the individual name of this unit.voidsetNationality(java.lang.String newNationality)Sets the nationality of this Unit.voidsetOwner(Player player)Sets the owner of thisOwnable.voidsetRole(Role role)Sets theRoleof thisUnit.voidsetRoleCount(int roleCount)Set the role count.voidsetState(Unit.UnitState s)Sets a new state for this unit and initializes the amount of work the unit has left.voidsetStateToAllChildren(Unit.UnitState state)Sets the given state to all the units that are carried.protected voidsetStateUnchecked(Unit.UnitState s)Actually set the unit state.voidsetStudent(Unit newStudent)Set the student unit.voidsetTeacher(Unit newTeacher)Set the teacher for this unit.voidsetTradeRoute(TradeRoute newTradeRoute)Set the unit trade route.voidsetTreasureAmount(int amount)Set the amount of treasure in this unit.voidsetTurnsOfTraining(int turnsOfTraining)Sets the number of turns this unit has been training.voidsetType(UnitType type)Sets the type of the unit.voidsetWorkImprovement(TileImprovement imp)Sets the TileImprovement that this pioneer is contributing to.voidsetWorkLeft(int workLeft)Sets the amount of work left.voidsetWorkType(GoodsType type)Set the type of goods this unit is producing in its current occupation.booleanshouldTakeTransportTo(Location loc)Should the unit use transport to get to a specified tile? True if: - The location is not null - The unit is not naval - The unit is not there already AND - there is no path OR the path uses an existing carrierprivate voidspendAllMoves()Set movesLeft to 0 if has some spent moves and it's in a colonyvoidswapWork(Unit other)Swap work with another unit.java.lang.StringtoShortString()Get a short description of this location.java.lang.StringtoString()java.lang.StringtoString(java.lang.String prefix)Gets a string representation of this unit.UnittrySwapExpert(java.util.List<Unit> others)Try to swap this unit if it is an expert for another that is doing its job.Locationup()Promote this location to a more meaningful one if possible.private intvalidateCurrentStop()Validate and return the current stop.protected voidwriteAttributes(FreeColXMLWriter xw)Write the attributes of this object to a stream.protected voidwriteChildren(FreeColXMLWriter xw)Write the children of this object to a stream.-
Methods inherited from class net.sf.freecol.common.model.GoodsLocation
addGoods, addGoods, addGoods, contains, containsGoods, getDisposables, getGoodsContainer, getGoodsCount, moveGoods, removeAll, removeGoods, removeGoods, removeGoods, setGoodsContainer
-
Methods inherited from class net.sf.freecol.common.model.UnitLocation
canAdd, clearUnitList, equipForRole, getCarrierForUnit, getColony, getFirstUnit, getIndianSettlement, getLastUnit, getLocationLabelFor, getNavalUnits, getTotalUnitCount, getUnitCapacity, getUnitCount, getUnitList, getUnits, hasCarrierWithSpace, intern, isEmpty, isFull, moveToFront, priceGoods
-
Methods inherited from class net.sf.freecol.common.model.FreeColGameObject
dispose, equals, fundamentalDispose, getGame, getSpecification, hashCode, internId, isDisposed, isInitialized, isInternable, readFromXML, setGame, setSpecification
-
Methods inherited from class net.sf.freecol.common.model.FreeColObject
addAbility, addFeatures, addModifier, addPropertyChangeListener, addPropertyChangeListener, apply, apply, applyModifiers, applyModifiers, arrayKey, compareIds, compareTo, containsAbilityKey, containsModifierKey, copy, copy, copy, copy, copyInCast, dumpObject, fireIndexedPropertyChange, fireIndexedPropertyChange, fireIndexedPropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getAbilities, getAbilities, getAbilities, getDefenceModifiers, getFeatureContainer, getFreeColObjectClass, getFreeColObjectClassByName, getId, getIdNumber, getIdType, getIdTypeByName, getModifiers, getModifiers, getModifiers, getObjectClassIndex, getPropertyChangeListeners, getPropertyChangeListeners, getPropertyChangeSupport, getSortedAbilities, getSortedModifiers, getSuffix, getSuffix, hasAbility, hasAbility, hasAbility, hasListeners, hasModifier, hasModifier, hasModifier, idEquals, invokeMethod, logFreeColObjects, readFromXMLPartial, removeAbilities, removeAbility, removeFeatures, removeModifier, removeModifiers, removePropertyChangeListener, removePropertyChangeListener, save, save, save, save, serialize, serialize, serialize, serialize, setId, toXML, toXML, toXMLPartial, toXMLPartial
-
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
-
Methods inherited from interface net.sf.freecol.common.model.Location
getId, getLocationImageKey
-
-
-
-
Field Detail
-
logger
private static final java.util.logging.Logger logger
-
UNIT_CLASS_INDEX
private static final int UNIT_CLASS_INDEX
Class index for units.- See Also:
- Constant Field Values
-
TAG
public static final java.lang.String TAG
- See Also:
- Constant Field Values
-
MANY_TURNS
public static final int MANY_TURNS
A large number of turns, denoting pathfinding failure. Do not use INFINITY as further calculation might use this.- See Also:
- Constant Field Values
-
DEFAULT_UNIT_VALUE
public static final int DEFAULT_UNIT_VALUE
Default value of unpriced units, used in evaluate_for.- See Also:
- Constant Field Values
-
CARGO_CHANGE
public static final java.lang.String CARGO_CHANGE
- See Also:
- Constant Field Values
-
MOVE_CHANGE
public static final java.lang.String MOVE_CHANGE
- See Also:
- Constant Field Values
-
ROLE_CHANGE
public static final java.lang.String ROLE_CHANGE
- See Also:
- Constant Field Values
-
locComparator
public static final java.util.Comparator<Unit> locComparator
Compare units by location.
-
typeRoleComparator
public static final java.util.Comparator<Unit> typeRoleComparator
A comparator to compare units by type, then role index, then the FCO order.
-
increasingSkillComparator
public static final java.util.Comparator<Unit> increasingSkillComparator
A comparator to compare units by increasing skill level.
-
decreasingSkillComparator
public static final java.util.Comparator<Unit> decreasingSkillComparator
A comparator to compare units by decreasing skill level.
-
settlementStartComparator
private static final java.util.Comparator<Settlement> settlementStartComparator
Comparator to rank settlements by accessibility by sea to Europe.
-
sentryPred
public static final java.util.function.Predicate<Unit> sentryPred
Useful predicate for finding sentried land units.
-
name
protected java.lang.String name
The individual name of this unit, not of the unit type.
-
owner
protected Player owner
The owner player.
-
type
protected UnitType type
The unit type.
-
state
protected Unit.UnitState state
Current unit state.
-
role
protected Role role
Current unit role.
-
roleCount
protected int roleCount
The amount of role-equipment this unit carries, subject to role.getMaximumCount(). Currently zero or one except for pioneers.
-
location
protected Location location
The current unit location.
-
entryLocation
protected Location entryLocation
The last entry location used by this unit.
-
movesLeft
protected int movesLeft
The number of moves this unit has left this turn.
-
workType
protected GoodsType workType
What type of goods this unit produces in its occupation.
-
experienceType
protected GoodsType experienceType
What type of goods this unit last earned experience producing.
-
experience
protected int experience
The mount of experience a unit has earned.
-
workLeft
protected int workLeft
The number of turns until the work is finished (e.g. sailing, improving), or '-1' if a Unit can stay in its state forever.
-
workImprovement
protected TileImprovement workImprovement
What is being improved (to be used only for PIONEERs - where they are working.
-
student
protected Unit student
The student of this Unit, if it has one.
-
teacher
protected Unit teacher
The teacher of this Unit, if it has one.
-
turnsOfTraining
protected int turnsOfTraining
Number of turns of training needed by this unit.
-
nationality
protected java.lang.String nationality
The original nationality.
-
ethnicity
protected java.lang.String ethnicity
The original ethnicity.
-
indianSettlement
protected IndianSettlement indianSettlement
The home settlement of a native unit.
-
hitPoints
protected int hitPoints
For now; only used by ships when repairing.
-
destination
protected Location destination
A destination for go-to moves.
-
tradeRoute
protected TradeRoute tradeRoute
The trade route this unit has.
-
currentStop
protected int currentStop
Which stop in a trade route the unit is going to.
-
treasureAmount
protected int treasureAmount
To be used only for type == TREASURE_TRAIN
-
attrition
protected int attrition
The attrition this unit has accumulated. At the moment, this equals the number of turns it has spent in the open.
-
visibleGoodsCount
protected int visibleGoodsCount
The amount of goods carried by this unit. This variable is only used by the clients. A negative value signals that the variable is not in use.- See Also:
getVisibleGoodsCount()
-
ATTRITION_TAG
private static final java.lang.String ATTRITION_TAG
- See Also:
- Constant Field Values
-
COUNT_TAG
private static final java.lang.String COUNT_TAG
- See Also:
- Constant Field Values
-
CURRENT_STOP_TAG
private static final java.lang.String CURRENT_STOP_TAG
- See Also:
- Constant Field Values
-
DESTINATION_TAG
private static final java.lang.String DESTINATION_TAG
- See Also:
- Constant Field Values
-
ENTRY_LOCATION_TAG
private static final java.lang.String ENTRY_LOCATION_TAG
- See Also:
- Constant Field Values
-
ETHNICITY_TAG
private static final java.lang.String ETHNICITY_TAG
- See Also:
- Constant Field Values
-
EXPERIENCE_TAG
private static final java.lang.String EXPERIENCE_TAG
- See Also:
- Constant Field Values
-
EXPERIENCE_TYPE_TAG
private static final java.lang.String EXPERIENCE_TYPE_TAG
- See Also:
- Constant Field Values
-
HIT_POINTS_TAG
private static final java.lang.String HIT_POINTS_TAG
- See Also:
- Constant Field Values
-
INDIAN_SETTLEMENT_TAG
private static final java.lang.String INDIAN_SETTLEMENT_TAG
- See Also:
- Constant Field Values
-
LOCATION_TAG
private static final java.lang.String LOCATION_TAG
- See Also:
- Constant Field Values
-
MOVES_LEFT_TAG
private static final java.lang.String MOVES_LEFT_TAG
- See Also:
- Constant Field Values
-
NAME_TAG
private static final java.lang.String NAME_TAG
- See Also:
- Constant Field Values
-
NATIONALITY_TAG
private static final java.lang.String NATIONALITY_TAG
- See Also:
- Constant Field Values
-
OWNER_TAG
private static final java.lang.String OWNER_TAG
- See Also:
- Constant Field Values
-
ROLE_TAG
private static final java.lang.String ROLE_TAG
- See Also:
- Constant Field Values
-
ROLE_COUNT_TAG
private static final java.lang.String ROLE_COUNT_TAG
- See Also:
- Constant Field Values
-
STATE_TAG
private static final java.lang.String STATE_TAG
- See Also:
- Constant Field Values
-
STUDENT_TAG
private static final java.lang.String STUDENT_TAG
- See Also:
- Constant Field Values
-
TRADE_ROUTE_TAG
private static final java.lang.String TRADE_ROUTE_TAG
- See Also:
- Constant Field Values
-
TEACHER_TAG
private static final java.lang.String TEACHER_TAG
- See Also:
- Constant Field Values
-
TREASURE_AMOUNT_TAG
private static final java.lang.String TREASURE_AMOUNT_TAG
- See Also:
- Constant Field Values
-
TURNS_OF_TRAINING_TAG
private static final java.lang.String TURNS_OF_TRAINING_TAG
- See Also:
- Constant Field Values
-
UNIT_TYPE_TAG
private static final java.lang.String UNIT_TYPE_TAG
- See Also:
- Constant Field Values
-
VISIBLE_GOODS_COUNT_TAG
private static final java.lang.String VISIBLE_GOODS_COUNT_TAG
- See Also:
- Constant Field Values
-
WORK_LEFT_TAG
private static final java.lang.String WORK_LEFT_TAG
- See Also:
- Constant Field Values
-
WORK_TYPE_TAG
private static final java.lang.String WORK_TYPE_TAG
- See Also:
- Constant Field Values
-
OLD_EQUIPMENT_TAG
private static final java.lang.String OLD_EQUIPMENT_TAG
- See Also:
- Constant Field Values
-
OLD_TILE_IMPROVEMENT_TAG
private static final java.lang.String OLD_TILE_IMPROVEMENT_TAG
- See Also:
- Constant Field Values
-
-
Constructor Detail
-
Unit
protected Unit(Game game)
Constructor for ServerUnit.- Parameters:
game- The enclosingGame.
-
Unit
public Unit(Game game, java.lang.String id)
Creates a newUnitwith the given identifier. The object should later be initialized by callingFreeColGameObject.readFromXML(FreeColXMLReader).- Parameters:
game- The enclosingGame.id- The object identifier.
-
-
Method Detail
-
initialize
private final void initialize()
Initialize the nationality and ethnicity.
-
getName
public java.lang.String getName()
Get the individual name of this unit.
-
setName
public void setName(java.lang.String newName)
Set the individual name of this unit.
-
getApparentOwnerName
public StringTemplate getApparentOwnerName()
Get the name of the apparent owner of this Unit, (like getOwner().getNationAsString() but handles pirates).- Returns:
- The name of the apparent owner of this
Unit.
-
getLabel
public StringTemplate getLabel()
Get a plain string template for a unit.- Returns:
- The
StringTemplateto describe the given unit.
-
getLabel
public StringTemplate getLabel(Unit.UnitLabelType ult)
Get a string template for a unit. The PLAIN template contains: - The type of the unit - A role if not the default - The specific name of the unit if it has one The NATIONAL template adds the nation The FULL template adds equipment annotations- Parameters:
ult- The type of label to get.- Returns:
- The
StringTemplateto describe the given unit.
-
getDescription
public java.lang.String getDescription()
Get the basic i18n description for this unit.- Returns:
- A
Stringdescribing this unit.
-
getDescription
public java.lang.String getDescription(Unit.UnitLabelType ult)
Get the basic i18n description for this unit.- Parameters:
ult- The label type required.- Returns:
- A
Stringdescribing this unit.
-
getCombatLabel
public StringTemplate getCombatLabel(Tile tile)
Get a label for the chance of success in a potential combat.- Parameters:
tile- TheTileto attack into.- Returns:
- A suitable label.
-
getDestinationLabel
public StringTemplate getDestinationLabel()
Get a destination label for this unit.- Returns:
- A
StringTemplatedescribing where this unit is going.
-
getUnitDestinationLabel
public static StringTemplate getUnitDestinationLabel(java.lang.String tag, Location destination, Player player)
Get a destination label for a given unit tag, destination and player.- Parameters:
tag- The unit tag for the "goingTo" message.destination- The destinationLocation.player- ThePlayerviewpoint.- Returns:
- A
StringTemplatedescribing the unit movement.
-
getRepairLabel
public StringTemplate getRepairLabel()
Get a string template describing the repair state of this unit.- Returns:
- A repair label.
-
getType
public final UnitType getType()
Get theUnitTypevalue.- Returns:
- The current
UnitType.
-
setType
public void setType(UnitType type)
Sets the type of the unit. -vis: Has visibility issues as the line of sight may change.- Parameters:
type- The new type of the unit.
-
changeType
public boolean changeType(UnitType unitType)
Changes the type of the unit. -vis: Has visibility issues as the line of sight may change.- Parameters:
unitType- The new type of the unit.- Returns:
- True if the type change succeeds.
-
getScoreValue
public int getScoreValue()
Score this unit. Just delegates to unit type for now.- Returns:
- The score for this unit.
-
isNaval
public boolean isNaval()
Checks if thisUnitis naval.- Returns:
- True if this is a naval
Unit.
-
isOwnerHidden
public boolean isOwnerHidden()
Is this a unit that hides its ownership?- Returns:
- True if the owner should be hidden from clients.
-
isUndead
public boolean isUndead()
Checks if this unit is an undead.- Returns:
- True if the unit is undead.
-
canCarryTreasure
public boolean canCarryTreasure()
Can this unit carry treasure (like a treasure train)?- Returns:
- True if this
Unitcan carry treasure.
-
canCaptureGoods
public boolean canCaptureGoods()
Can this unit capture enemy goods?- Returns:
- True if this
Unitis capable of capturing goods.
-
isTradingUnit
public boolean isTradingUnit()
Checks if this is a tradingUnit, meaning that it can trade with settlements.- Returns:
- True if this is a trading unit.
-
isColonist
public boolean isColonist()
Checks if thisUnitis a `colonist'. A unit is a colonist if it is European and can build a newColony.- Returns:
- True if this unit is a colonist.
-
isCarrier
public boolean isCarrier()
Checks if thisUnitis able to carryLocatables.- Returns:
- True if this unit can carry goods or other units.
-
isPerson
public boolean isPerson()
Checks if this unit is a person, that is not a ship or wagon.- Returns:
- True if this unit is a person.
-
getState
public Unit.UnitState getState()
Gets the state of thisUnit.- Returns:
- The state of this
Unit.
-
checkSetState
public boolean checkSetState(Unit.UnitState s)
Checks if aUnitcan get the given state set.- Parameters:
s- The new state for this Unit. Should be one of {UnitState.ACTIVE, FORTIFIED, ...}.- Returns:
- True if the
Unitstate can be changed to the new value.
-
setState
public void setState(Unit.UnitState s)
Sets a new state for this unit and initializes the amount of work the unit has left. If the work needs turns to be completed (for instance when plowing), then the moves the unit has still left will be used up. Some work (basically building a road with a hardy pioneer) might actually be finished already in this method-call, in which case the state is set back to UnitState.ACTIVE.- Parameters:
s- The new state for this Unit. Should be one of {UnitState.ACTIVE, UnitState.FORTIFIED, ...}.
-
setStateUnchecked
protected void setStateUnchecked(Unit.UnitState s)
Actually set the unit state.- Parameters:
s- The newUnitState.
-
setStateToAllChildren
public void setStateToAllChildren(Unit.UnitState state)
Sets the given state to all the units that are carried.- Parameters:
state- TheUnitStateto set..
-
changeOwner
public void changeOwner(Player owner)
Change the owner of this unit. -vis: This routine calls setOwner() and thus has visibility implications. Ideally it should be in ServerUnit but we keep it here for the benefit of the test suite.- Parameters:
owner- The new ownerPlayer.
-
getRole
public Role getRole()
Gets the unit role.- Returns:
- The
Roleof thisUnit.
-
setRole
public void setRole(Role role)
Sets theRoleof thisUnit.- Parameters:
role- The newRole.
-
getRoleCount
public int getRoleCount()
Get the role count.- Returns:
- The current role count.
-
setRoleCount
public void setRoleCount(int roleCount)
Set the role count.- Parameters:
roleCount- The new role count.
-
hasDefaultRole
public boolean hasDefaultRole()
Does this unit have the default role?- Returns:
- True if the unit has the default
Role.
-
getRoleSuffix
public java.lang.String getRoleSuffix()
Get the last part of the role identifier, which is often used as part of a message key.- Returns:
- The role suffix.
-
changeRole
public void changeRole(Role role, int roleCount)
Change the current role of this unit.- Parameters:
role- The newRole.roleCount- The new role count.
-
changeRoleCount
public boolean changeRoleCount(int delta)
Change the current role count. On zero, revert to default role.- Parameters:
delta- The change to apply to the role count.- Returns:
- True if the role count reached zero.
-
roleIsAvailable
public boolean roleIsAvailable(Role role)
Is a role available to this unit?- Parameters:
role- TheRoleto test.- Returns:
- True if the role is available to this unit.
-
getAvailableRolesList
public java.util.List<Role> getAvailableRolesList(java.util.List<Role> roles)
Filter a list of roles to return only those available to this unit.- Parameters:
roles- The list ofRoles to filter, if null all available roles are used.- Returns:
- A list of available
Roles.
-
getAvailableRoles
public java.util.stream.Stream<Role> getAvailableRoles(java.util.List<Role> roles)
Filter a list of roles to return only those available to this unit, returning a stream.- Parameters:
roles- The list ofRoles to filter, if null all available roles are used.- Returns:
- A stream of available
Roles.
-
getMilitaryRole
public Role getMilitaryRole()
Get a military role for this unit.- Returns:
- A military
Role, or null if none found.
-
getGoodsDifference
public java.util.List<AbstractGoods> getGoodsDifference(Role role, int roleCount)
Get the change in goods required to change to a new role/count.- Parameters:
role- The newRoleto change to.roleCount- The new role count.- Returns:
- A list of
AbstractGoodsdefining the change in goods required.
-
setLocationNoUpdate
public void setLocationNoUpdate(Location newLocation)
Sets the units location without updating any other variables get/setLocation are in Locatable interface. -vis: This routine changes player visibility.- Parameters:
newLocation- The newLocation.
-
isOnCarrier
public boolean isOnCarrier()
Verifies if the unit is aboard a carrier- Returns:
- True if the unit is aboard a carrier.
-
isOnTile
public boolean isOnTile()
Is this unit on a tile?- Returns:
- True if the unit is on a tile.
-
getCarrier
public Unit getCarrier()
Gets the carrier this unit is aboard if any.- Returns:
- The carrier this unit is aboard, or null if none.
-
isAtSea
public boolean isAtSea()
Checks whether thisUnitis at sea off the map, or on board of a carrier that is.- Returns:
- True if at sea.
-
isInMission
public boolean isInMission()
Checks if this unit is running a mission.- Returns:
- True if this unit is running a mission.
-
isInColony
public boolean isInColony()
Checks whether this unit is working inside a colony.- Returns:
- True if in colony.
-
hasTile
public boolean hasTile()
Is this unit on a tile?- Returns:
- True if this unit is on a tile.
-
getWorkLocation
public WorkLocation getWorkLocation()
Gets the work location this unit is working in.- Returns:
- The current
WorkLocation, or null if none.
-
getWorkTile
public Tile getWorkTile()
Get the work tile this unit is working in, if any.- Returns:
- The current work
Tile, if any.
-
getEntryLocation
public Location getEntryLocation()
Gets the entry location for this unit to use when returning fromEurope.- Returns:
- The entry
Location.
-
setEntryLocation
public void setEntryLocation(Location entryLocation)
Sets the entry location in which this unit will be put when returning fromEurope.- Parameters:
entryLocation- The new entryLocation.- See Also:
getEntryLocation()
-
getFullEntryLocation
public Tile getFullEntryLocation()
Gets the entry tile for this unit, or if null the default entry location for the owning player.- Returns:
- The entry
Tile.
-
getMovesLeft
public int getMovesLeft()
Get the moves left this turn.- Specified by:
getMovesLeftin interfaceMovable- Returns:
- The number of moves this
Unithas left.
-
getCarriedUnitById
public Unit getCarriedUnitById(java.lang.String id)
Get a carried unit by identifier.- Parameters:
id- The identifier of the carried unit.- Returns:
- The
Unitfound, or null if not present.
-
setMovesLeft
public void setMovesLeft(int moves)
Sets the moves left this turn.- Parameters:
moves- The new amount of moves left thisUnitshould have.
-
getWorkType
public GoodsType getWorkType()
Gets the type of goods this unit is producing in its current occupation.- Returns:
- The type of goods this unit is producing.
-
setWorkType
public void setWorkType(GoodsType type)
Set the type of goods this unit is producing in its current occupation.- Parameters:
type- TheGoodsTypeto produce.
-
changeWorkType
public void changeWorkType(GoodsType type)
Change the type of goods this unit is producing in its current occupation. Updates the work location production and the unit experience type if necessary.- Parameters:
type- TheGoodsTypeto produce.
-
getExperienceType
public GoodsType getExperienceType()
Gets the type of goods this unit has accrued experience producing.- Returns:
- The
GoodsTypethis unit would produce.
-
changeExperienceType
public void changeExperienceType(GoodsType type)
Sets the type of goods this unit has accrued experience producing.- Parameters:
type- TheGoodsTypethis unit would produce.
-
getExperience
public int getExperience()
Gets the experience of thisUnitat its current experienceType.- Returns:
- The experience of this
Unitat its current experienceType. - See Also:
modifyExperience(int)
-
setExperience
public void setExperience(int experience)
Sets the experience of thisUnitat its current experienceType.- Parameters:
experience- The new experience of thisUnitat its current experienceType.- See Also:
modifyExperience(int)
-
modifyExperience
public void modifyExperience(int value)
Modifies the experience of thisUnitat its current experienceType.- Parameters:
value- The value by which to modify the experience of thisUnit.- See Also:
getExperience()
-
getWorkLeft
public int getWorkLeft()
Gets the amount of work left.- Returns:
- The amount of work left.
-
setWorkLeft
public void setWorkLeft(int workLeft)
Sets the amount of work left.- Parameters:
workLeft- The new amount of work left.
-
getWorkTurnsLeft
public int getWorkTurnsLeft()
Get the number of turns of work left.- Returns:
- The number of turns of work left.
-
getWorkImprovement
public TileImprovement getWorkImprovement()
Gets the TileImprovement that this pioneer is contributing to.- Returns:
- The
TileImprovementthe pioneer is working on.
-
setWorkImprovement
public void setWorkImprovement(TileImprovement imp)
Sets the TileImprovement that this pioneer is contributing to.- Parameters:
imp- The newTileImprovementthe pioneer is to work on.
-
getStudent
public final Unit getStudent()
Get the unit being taught.- Returns:
- A student
Unitif any.
-
setStudent
public final void setStudent(Unit newStudent)
Set the student unit.- Parameters:
newStudent- The new studentUnit.
-
getTeacher
public final Unit getTeacher()
Get the unit teaching this one.- Returns:
- A teacher
Unit.
-
setTeacher
public final void setTeacher(Unit newTeacher)
Set the teacher for this unit.- Parameters:
newTeacher- The new teacherUnit.
-
getTurnsOfTraining
public int getTurnsOfTraining()
Gets the number of turns this unit has been training.- Returns:
- The number of turns of training this
Unithas given. - See Also:
setTurnsOfTraining(int),getNeededTurnsOfTraining()
-
setTurnsOfTraining
public void setTurnsOfTraining(int turnsOfTraining)
Sets the number of turns this unit has been training.- Parameters:
turnsOfTraining- The number of turns of training thisUnithas given.- See Also:
getNeededTurnsOfTraining()
-
getNeededTurnsOfTraining
public int getNeededTurnsOfTraining()
Gets the number of turns this unit has to train to educate a student. This value is only meaningful for units that can be put in a school.- Returns:
- The turns of training needed to teach its current type to a free colonist or to promote an indentured servant or a petty criminal.
- See Also:
getTurnsOfTraining()
-
getUnitChange
public UnitTypeChange getUnitChange(java.lang.String change)
Get a unit change for this unit.- Parameters:
change- The identifier for the required change type.- Returns:
- The
UnitChangefound, or null if the change is impossible.
-
getUnitChange
public UnitTypeChange getUnitChange(java.lang.String change, UnitType toType)
Get a unit change for this unit.- Parameters:
change- The identifier for the required change type.toType- AUnitTypeto change to.- Returns:
- The
UnitChangefound, or null if the change is impossible.
-
getUnitChange
public UnitTypeChange getUnitChange(java.lang.String change, UnitType toType, Player player)
Get a unit change for this unit, including the ownership check.- Parameters:
change- The identifier for the required change type.toType- AUnitTypeto change to.player- The expectedPlayerthat will own the unit.- Returns:
- The
UnitChangefound, or null if the change is impossible.
-
getTeachingType
public UnitType getTeachingType(UnitType teacherType)
Get the skill another unit type can teach this unit. Public for the test suite.- Parameters:
teacherType- TheUnitTypeto teach this unit.- Returns:
- The
UnitType(skill) this unit can learn.
-
getTeachingType
public UnitType getTeachingType(Unit teacher)
Get the skill another unit can teach this unit.- Parameters:
teacher- TheUnitto teach this unit.- Returns:
- The
UnitType(skill) this unit can learn.
-
canBeStudent
public boolean canBeStudent(Unit teacher)
Can this unit be a student of a teacher unit?- Parameters:
teacher- The teacherUnitwhich is trying to teach it.- Returns:
- True if the unit can be taught by the teacher.
-
getNationality
public final java.lang.String getNationality()
Gets the nationality of this Unit. Nationality represents a Unit's personal allegiance to a nation. This may conflict with who currently issues orders to the Unit (the owner).- Returns:
- The nationality of this Unit.
-
setNationality
public final void setNationality(java.lang.String newNationality)
Sets the nationality of this Unit. A unit will change nationality when it switches owners willingly. Currently only Converts do this, but it opens the possibility of naturalisation.- Parameters:
newNationality- The new nationality of this Unit.
-
getEthnicity
public final java.lang.String getEthnicity()
Gets the ethnicity of this Unit. Ethnicity is inherited from the inhabitants of the place where the Unit was born. Allows former converts to become native-looking colonists.- Returns:
- The ethnicity of this Unit.
-
setEthnicity
public final void setEthnicity(java.lang.String newEthnicity)
Sets the ethnicity of this Unit.- Parameters:
newEthnicity- The new ethnicity of this Unit.
-
hasNativeEthnicity
public boolean hasNativeEthnicity()
Identifies whether this unit came from a native tribe.- Returns:
- Whether this unit looks native or not.
-
getHomeIndianSettlement
public IndianSettlement getHomeIndianSettlement()
Gets theIndianSettlementhome for this unit.- Returns:
- The home
IndianSettlementof this unit.
-
setHomeIndianSettlement
public void setHomeIndianSettlement(IndianSettlement indianSettlement)
Sets the homeIndianSettlementfor this unit.- Parameters:
indianSettlement- TheIndianSettlementthat this unit considers to be its home.
-
changeHomeIndianSettlement
public IndianSettlement changeHomeIndianSettlement(IndianSettlement indianSettlement)
Changes the homeIndianSettlementfor this unit.- Parameters:
indianSettlement- TheIndianSettlementthat should now own thisUnitand be considered this unit's home.- Returns:
- The old
IndianSettlement.
-
getHitPoints
public int getHitPoints()
Gets the unit hit points. This is currently only used for damaged ships, but might get an extended use later.- Returns:
- The hit points this
Unithas. - See Also:
UnitType.getHitPoints()
-
setHitPoints
public void setHitPoints(int hitPoints)
Sets the hit points for this unit.- Parameters:
hitPoints- The new hit points for this unit.
-
isDamaged
public boolean isDamaged()
Checks if this unit is under repair.- Returns:
- True if under repair.
-
getTurnsForRepair
public int getTurnsForRepair()
Get how many turns left to be repaired- Returns:
- The number of turns left to be repaired.
-
getDestination
public Location getDestination()
Get the destination of this unit.- Returns:
- The destination
Locationof thisUnit.
-
setDestination
public void setDestination(Location newDestination)
Sets the destination of this unit.- Parameters:
newDestination- The new destinationLocation.
-
getTradeRoute
public final TradeRoute getTradeRoute()
Get the unit trade route, if any.- Returns:
- The
TradeRoute, or null if none.
-
setTradeRoute
public final void setTradeRoute(TradeRoute newTradeRoute)
Set the unit trade route.- Parameters:
newTradeRoute- The newTradeRoutevalue.
-
getStop
public TradeRouteStop getStop()
Get the stop the unit is heading for or at.- Returns:
- The target
TradeRouteStop.
-
getCurrentStops
public java.util.List<TradeRouteStop> getCurrentStops()
Get the stop the unit is heading for or at.- Returns:
- The target
TradeRouteStop.
-
getCurrentStop
public int getCurrentStop()
Get the current trade route stop.- Returns:
- The current stop index.
-
setCurrentStop
public void setCurrentStop(int currentStop)
Set the current stop.- Parameters:
currentStop- A new value for the currentStop.
-
validateCurrentStop
private int validateCurrentStop()
Validate and return the current stop.- Returns:
- The current stop index, or negative on failure.
-
atStop
public boolean atStop(TradeRouteStop stop)
Convenience function to check if a unit is at a stop.- Parameters:
stop- TheTradeRouteStopto check.- Returns:
- True if the unit is at the given stop.
-
getTradeLocation
public TradeLocation getTradeLocation()
Get the current trade location.- Returns:
- The
TradeLocationfor this unit.
-
getTreasureAmount
public int getTreasureAmount()
Get the current amount of treasure in this unit.- Returns:
- The amount of treasure.
- Throws:
java.lang.IllegalStateException- if this is not a treasure carrying unit.
-
setTreasureAmount
public void setTreasureAmount(int amount)
Set the amount of treasure in this unit.- Parameters:
amount- The new amount of treasure.
-
getAttrition
public int getAttrition()
Gets the attrition of this unit.- Returns:
- The attrition of this unit.
-
setAttrition
public void setAttrition(int attrition)
Sets the attrition of this unit.- Parameters:
attrition- The new attrition of this unit.
-
getVisibleGoodsCount
public int getVisibleGoodsCount()
Get the visible amount of goods that is carried by this unit.- Returns:
- The visible amount of goods carried by this
Unit.
-
getAutomaticRole
public Role getAutomaticRole()
Gets a role that can be equipped automatically assumed in case of an attack. Paul Revere makes an unarmed colonist in a settlement pick up a stock-piled musket if attacked, so the bonus should be applied for unarmed colonists inside colonies where there are muskets available. Natives can also auto-arm.- Returns:
- A
Rolethat can be automatically assumed by this unit, or null if none.
-
canCaptureEquipment
public Role canCaptureEquipment(Role role)
After winning a battle, can this unit capture the loser's role equipment?- Parameters:
role- The loser unitRole.- Returns:
- The
Roleavailable to this unit as a result of capturing the loser equipment.
-
losingEquipmentKillsUnit
public boolean losingEquipmentKillsUnit()
Does losing a piece of equipment mean the death of this unit?- Returns:
- True if the unit is doomed.
-
losingEquipmentDemotesUnit
public boolean losingEquipmentDemotesUnit()
Does losing equipment mean the demotion of this unit?- Returns:
- True if the unit is to be demoted.
-
isArmed
public boolean isArmed()
Does the unit have arms?- Returns:
- True if the unit has arms.
-
isMounted
public boolean isMounted()
Does the unit have a mount?- Returns:
- True if the unit have a mount.
-
isBeached
public boolean isBeached()
Is the unit a beached ship?- Returns:
- True if the unit is a beached ship.
-
isBeached
public boolean isBeached(Tile tile)
Would this unit be beached if it was on a particular tile?- Parameters:
tile- TheTileto check.- Returns:
- True if the unit is a beached ship.
-
isDefensiveUnit
public boolean isDefensiveUnit()
Checks if this is an defensive unit. That is: a unit which can be used to defend aSettlement. Note! As this method is used by the AI it really means that the unit can defend as is. To be specific an unarmed colonist is not defensive yet, even if Paul Revere and stockpiled muskets are available. That check is only performed on an actual attack. A settlement is lost when there are no more defensive units.- Returns:
- True if this is a defensive unit meaning it can be used
to defend a
Colony. This would normally mean that a defensive unit also will be offensive.
-
isOffensiveUnit
public boolean isOffensiveUnit()
Checks if this is an offensive unit. That is, one that can attack other units.- Returns:
- True if this is an offensive unit.
-
canAmbush
public boolean canAmbush(Unit defender)
Can this unit ambush another?- Parameters:
defender- The defendingUnit.- Returns:
- True if an ambush attack is possible.
-
betterDefender
public static boolean betterDefender(Unit defender, double defenderPower, Unit other, double otherPower)
Is an alternate unit a better defender than the current choice. Prefer if there is no current defender, or if the alternate unit is better armed, or provides greater defensive power and does not replace a defensive unit defender with a non-defensive unit.- Parameters:
defender- The current defenderUnit.defenderPower- Its defence power.other- An alternateUnit.otherPower- Its defence power.- Returns:
- True if the other unit should be preferred.
-
getRepairLocation
public Location getRepairLocation()
Finds the closestLocationto this tile where this ship can be repaired, excluding the current colony.- Returns:
- The closest
Locationwhere a ship can be repaired.
-
damageShip
public void damageShip(Location repair)
Damage this unit (which should be a ship).- Parameters:
repair- ALocationto send the ship to for repair.
-
getMoveCost
public int getMoveCost(Tile target)
Gets the cost of moving thisUnitonto the givenTile. A call togetMoveType(Tile)will returnMOVE_NO_MOVES, if returns a move cost larger than themoves left.- Parameters:
target- TheTilethisUnitwill move onto.- Returns:
- The cost of moving this unit onto the given
Tile.
-
getMoveCost
public int getMoveCost(Tile from, Tile target, int ml)
Gets the cost of moving thisUnitfrom the givenTileonto the givenTile. A call togetMoveType(Tile, Tile, int)will returnMOVE_NO_MOVES, ifgetMoveCost(net.sf.freecol.common.model.Tile)returns a move cost larger than thegetMovesLeft()moves left.- Parameters:
from- TheTilethisUnitwill move from.target- TheTilethisUnitwill move onto.ml- The amount of moves this Unit has left.- Returns:
- The cost of moving this unit onto the given
Tile.
-
getMoveType
public Unit.MoveType getMoveType(Direction direction)
Gets the type of a move made in a specified direction.- Parameters:
direction- TheDirectionof the move.- Returns:
- The move type.
-
getMoveType
public Unit.MoveType getMoveType(Tile target)
Gets the type of a move that is made when moving from one tile to another.- Parameters:
target- The targetTileof the move.- Returns:
- The move type.
-
getMoveType
public Unit.MoveType getMoveType(Tile from, Tile target, int ml)
Gets the type of a move that is made when moving from one tile to another.- Parameters:
from- The originTileof the move.target- The targetTileof the move.ml- The amount of moves this unit has left.- Returns:
- The move type.
-
getSimpleMoveType
public Unit.MoveType getSimpleMoveType(Tile from, Tile target)
Gets the type of a move that is made when moving from one tile to another, without checking if the unit has moves left or logging errors.- Parameters:
from- The originTileof the move.target- The targetTileof the move.- Returns:
- The move type, which will be one of the extended illegal move types on failure.
-
getSimpleMoveType
public Unit.MoveType getSimpleMoveType(Tile target)
Gets the type of a move that is made when moving from one tile to another, without checking if the unit has moves left or logging errors.- Parameters:
target- The targetTileof the move.- Returns:
- The move type, which will be one of the extended illegal move types on failure.
-
getSimpleMoveType
public Unit.MoveType getSimpleMoveType(Direction direction)
Gets the type of a move made in a specified direction, without checking if the unit has moves left or logging errors.- Parameters:
direction- The direction of the move.- Returns:
- The move type.
-
getNavalMoveType
private Unit.MoveType getNavalMoveType(Tile from, Tile target)
Gets the type of a move that is made when moving a naval unit from one tile to another.- Parameters:
from- The originTileof the move.target- The targetTileof the move.- Returns:
- The move type.
-
getLandMoveType
private Unit.MoveType getLandMoveType(Tile from, Tile target)
Gets the type of a move that is made when moving a land unit to from one tile to another.- Parameters:
from- The originTileof the move.target- The targetTileof the move.- Returns:
- The move type.
-
getTradeMoveType
private Unit.MoveType getTradeMoveType(Settlement settlement)
Get theMoveTypewhen moving a trading unit to a settlement.- Parameters:
settlement- TheSettlementto move to.- Returns:
- The appropriate
MoveType.
-
getLearnMoveType
private Unit.MoveType getLearnMoveType(Tile from, Settlement settlement)
Get theMoveTypewhen moving a colonist to a settlement.- Parameters:
from- TheTileto move from.settlement- TheSettlementto move to.- Returns:
- The appropriate
MoveType.
-
getMissionaryMoveType
private Unit.MoveType getMissionaryMoveType(Tile from, Settlement settlement)
Get theMoveTypewhen moving a missionary to a settlement.- Parameters:
from- TheTileto move from.settlement- TheSettlementto move to.- Returns:
- The appropriate
MoveType.
-
allowMoveFrom
private boolean allowMoveFrom(Tile from)
Is this unit allowed to move from a source tile? Implements the restrictions on moving from water.- Parameters:
from- TheTileto consider.- Returns:
- True if the move is allowed.
-
allowContact
private boolean allowContact(Settlement settlement)
Is this unit allowed to contact a settlement?- Parameters:
settlement- TheSettlementto consider.- Returns:
- True if the contact is allowed.
-
isTileAccessible
public boolean isTileAccessible(Tile tile)
Does a basic check whether a unit can ever expect to move to a tile.- Parameters:
tile- The codeTileto check.- Returns:
- True if some sort of legal move to the tile exists, including special cases where there is an interaction but the unit does not actually move, such as trade.
-
getInitialMovesLeft
public int getInitialMovesLeft()
Gets the amount of moves this unit has at the beginning of each turn.- Specified by:
getInitialMovesLeftin interfaceMovable- Returns:
- The amount of moves this unit has at the beginning of each turn.
-
getMovesAsString
public java.lang.String getMovesAsString()
Make a label showing the unit moves left.- Returns:
- A movement label.
-
getSailTurns
public int getSailTurns()
Gets the number of turns this unit will need to sail to/from Europe.- Returns:
- The number of turns to sail to/from Europe.
-
canMoveToHighSeas
public boolean canMoveToHighSeas()
Checks if thisUnitcan be moved to the high seas from its current location.- Returns:
- True if this unit can move immediately to the high seas.
-
canBuildColony
public boolean canBuildColony()
Check if this unit can build a colony. Does not consider whether the tile where the unit is located is suitable,- Returns:
trueif this unit can build a colony.- See Also:
Player.canClaimToFoundSettlement(Tile)
-
isAtLocation
public boolean isAtLocation(Location loc)
Is this unit at a specified location?- Parameters:
loc- TheLocationto test.- Returns:
- True if the locations are the same, or on the same tile.
-
getBestEntryTile
public Tile getBestEntryTile(Tile tile)
Gets the best (closest) entry location for this unit to reach a given tile.- Parameters:
tile- The targetTile.- Returns:
- The best entry location tile to arrive on the map at, or null if none found.
-
resolveDestination
public Location resolveDestination()
Resolves a destination for a unit on the high seas. That is, the location where the unit will appear when it leaves the high seas, which will either be Europe or a tile.- Returns:
- The location the unit should appear next after leaving the high seas.
-
spendAllMoves
private void spendAllMoves()
Set movesLeft to 0 if has some spent moves and it's in a colony- See Also:
add(Locatable),remove(Locatable)
-
isReadyToTrade
public boolean isReadyToTrade()
Is this unit ready to operate a trade route?- Returns:
- True if the unit is ready to trade.
-
readyAndAble
private boolean readyAndAble()
Basic checks for whether a unit is usable ATM.- Returns:
- True if the unit might be useful at present.
-
couldMove
public boolean couldMove()
Is this unit a suitable `next active unit', that is, the unit needs to be currently movable by the player. Used as a predicate in Player.nextActiveUnitIterator.- Returns:
- True if this unit could still be moved by the player.
-
goingToDestination
public boolean goingToDestination()
Is this unit a suitable `going-to unit', that is, the unit needs have a valid destination and be able to progress towards it. Used as a predicate in Player.nextGoingToUnitIterator.- Returns:
- True if this unit can go to its destination.
-
followingTradeRoute
public boolean followingTradeRoute()
Is this unit available to move along a trade route? Used as a predicate in Player.nextTradeRouteUnitIterator.- Returns:
- True if this unit can follow a trade route.
-
getPathStartLocation
public Location getPathStartLocation()
Gets a suitable location to start path searches for a unit. Must handle all the cases where the unit is off the map, and take account of the use of a carrier.- Returns:
- A suitable starting location, or null if none found.
-
shouldTakeTransportTo
public boolean shouldTakeTransportTo(Location loc)
Should the unit use transport to get to a specified tile? True if: - The location is not null - The unit is not naval - The unit is not there already AND - there is no path OR the path uses an existing carrier- Parameters:
loc- TheLocationto go to.- Returns:
- True if the unit should use transport.
-
getTrivialPath
public PathNode getTrivialPath()
Gets the trivial path for this unit. That is, the path to the nearest available safe settlement.- Returns:
- A path to the trivial target, or null if none found.
-
getPathComparator
private java.util.Comparator<Tile> getPathComparator(Location start, Unit carrier, CostDecider costDecider)
Get a comparator to rank locations by proximity to a start location, using this unit+optional carrier and cost decider.- Parameters:
start- The startingLocation.carrier- An optional carrierUnit.costDecider- An optionCostDecider.- Returns:
- A suitable
Comparator.
-
findPath
public PathNode findPath(Location end)
Finds the fastest path from the current location to the specified one. No carrier is provided, and the default cost decider for this unit is used.- Parameters:
end- TheLocationin which the path ends.- Returns:
- A
PathNodefrom the current location to the end location, or null if none found.
-
findPath
public PathNode findPath(Location start, Location end)
Finds the fastest path from a given location to a specified one. No carrier is provided, and the default cost decider for this unit is used.- Parameters:
start- TheLocationat which the path starts.end- TheLocationin which the path ends.- Returns:
- A
PathNodefrom the current location to the end location, or null if none found.
-
findPath
public PathNode findPath(Location start, Location end, Unit carrier)
Finds the fastest path from a given location to a specified one, with an optional carrier. The default cost decider for the relevant unit is used.- Parameters:
start- TheLocationat which the path starts.end- TheLocationin which the path ends.carrier- An optional carrierUnitto use.- Returns:
- A
PathNodefrom the current location to the end location, or null if none found.
-
findPath
public PathNode findPath(Location start, Location end, Unit carrier, CostDecider costDecider, LogBuilder lb)
Finds a quickest path between specified locations, optionally using a carrier and special purpose cost decider.- Parameters:
start- TheLocationto start at.end- TheLocationto end at.carrier- An optional carrierUnitto carry the unit.costDecider- An optionalCostDeciderfor determining the movement costs (uses default cost deciders for the unit/s if not provided).lb- An optionalLogBuilderto log the path to.- Returns:
- A
PathNode, or null if no path is found. - Throws:
java.lang.IllegalArgumentException- if the destination is null, (FIXME) this is a temporary debugging measure.
-
realStart
private Location realStart(Location start, Unit carrier)
Unified argument tests for full path searches, which then finds the actual starting location for the path. Deals with special cases like starting on a carrier and/or high seas.- Parameters:
start- TheLocationin which the path starts from.carrier- An optional naval carrierUnitto use.- Returns:
- The actual starting location.
- Throws:
java.lang.IllegalArgumentException- If there are any argument problems.
-
search
public PathNode search(Location start, GoalDecider gd, CostDecider cd, int maxTurns, Unit carrier)
Convenience wrapper for theMap.search(net.sf.freecol.common.model.Unit, net.sf.freecol.common.model.Location, net.sf.freecol.common.model.pathfinding.GoalDecider, net.sf.freecol.common.model.pathfinding.CostDecider, int, net.sf.freecol.common.model.Unit, net.sf.freecol.common.util.LogBuilder)function.- Parameters:
start- TheLocationto start the search from.gd- The object responsible for determining whether a givenPathNodeis a goal or not.cd- An optionalCostDeciderresponsible for determining the path cost.maxTurns- The maximum number of turns the givenUnitis allowed to move. This is the maximum search range for a goal.carrier- An optional naval carrierUnitto use.- Returns:
- The path to a goal, or null if none can be found.
-
findPathToNeighbour
public PathNode findPathToNeighbour(Location start, Tile end, Unit carrier, CostDecider costDecider)
Finds a quickest path to a neighbouring tile to a specified target tile, optionally using a carrier and special purpose cost decider.- Parameters:
start- TheLocationto start at.end- TheTileto end at a neighbour of.carrier- An optional carrierUnitto carry the unit.costDecider- An optionalCostDeciderfor determining the movement costs (uses default cost deciders for the unit/s if not provided).- Returns:
- A
PathNode, or null if no path is found.
-
getTurnsToReach
public int getTurnsToReach(Location end)
Gets the number of turns required for this unit to reach a destination location from its current position. If the unit is currently on a carrier, it will be used.- Parameters:
end- The destinationLocation.- Returns:
- The number of turns it will take to reach the destination,
or
MANY_TURNSif no path can be found.
-
getTurnsToReach
public int getTurnsToReach(Location start, Location end)
Gets the number of turns required for this unit to reach a destination location from a starting location. If the unit is currently on a carrier, it will be used.- Parameters:
start- TheLocationto start the search from.end- The destinationLocation.- Returns:
- The number of turns it will take to reach the
end, orMANY_TURNSif no path can be found.
-
getTurnsToReach
public int getTurnsToReach(Location start, Location end, Unit carrier, CostDecider costDecider)
Gets the number of turns required for this unit to reach a destination location from a starting location, using an optional carrier and cost decider.- Parameters:
start- TheLocationto start the search from.end- The destinationLocation.carrier- An optional carrierUnitto use.costDecider- An optionalCostDeciderto score the path with.- Returns:
- The number of turns it will take to reach the
end, orMANY_TURNSif no path can be found.
-
getClosestColony
public Colony getClosestColony(java.util.List<Colony> colonies)
Get the colony that can be reached by this unit in the least number of turns.- Parameters:
colonies- A list ofColonys.- Returns:
- The nearest
Colony, or null if none found.
-
getClosestColony
public Colony getClosestColony(java.util.stream.Stream<Colony> colonies)
Get the colony that can be reached by this unit in the least number of turns.- Parameters:
colonies- A stream ofColonys.- Returns:
- The nearest
Colony, or null if none found.
-
findOurNearestSettlement
public PathNode findOurNearestSettlement(boolean excludeStart, int range, boolean coastal)
Find a path for this unit to the nearest settlement with the same owner that is reachable without a carrier.- Parameters:
excludeStart- If true, ignore any settlement the unit is currently in.range- An upper bound on the number of moves.coastal- If true, the settlement must have a path to Europe.- Returns:
- The nearest matching settlement if any, otherwise null.
-
findOurNearestSettlement
public PathNode findOurNearestSettlement(Tile startTile, boolean excludeStart, int range, boolean coastal)
Find a path for this unit to the nearest settlement with the same owner that is reachable without a carrier.- Parameters:
startTile- TheTileto start searching from.excludeStart- If true, ignore any settlement the unit is currently in.range- An upper bound on the number of moves.coastal- If true, the settlement must have a path to Europe.- Returns:
- The nearest matching settlement if any, otherwise null.
-
findOurNearestSettlement
public PathNode findOurNearestSettlement()
Find a path for this unit to the nearest settlement with the same owner that is reachable without a carrier.- Returns:
- A path to the nearest settlement if any, otherwise null.
-
findOurNearestPort
public PathNode findOurNearestPort()
Find a path for this unit to the nearest settlement with the same owner that is reachable without a carrier and is connected to Europe by sea, or Europe if it is closer.- Returns:
- A path to the nearest settlement if any, otherwise null (for now including if in Europe or at sea).
-
findIntermediatePort
public PathNode findIntermediatePort(Location dst)
Find a path to a settlement nearer to a destination. Used to find where to deliver goods to/from inland colonies, or when blocked.- Parameters:
dst- The destinationLocation.- Returns:
- A path to the port, or null if none found.
-
findOurNearestOtherSettlement
public PathNode findOurNearestOtherSettlement()
Find a path for this unit to the nearest settlement with the same owner that is reachable without a carrier, excepting any on the current tile.- Returns:
- The nearest settlement if any, otherwise null.
-
canAttack
public boolean canAttack(Unit defender)
Can this unit attack a specified defender? A naval unit can never attack a land unit or settlement, but a land unit *can* attack a naval unit if it is beached. Otherwise naval units can only fight at sea, land units only on land.- Parameters:
defender- The defendingUnit.- Returns:
- True if this unit can attack.
-
searchForDanger
public PathNode searchForDanger(int range, float threat)
Searches for a unit that is a credible threatening unit to this unit within a range.- Parameters:
range- The number of turns to search for a threat in.threat- The maximum tolerable probability of a potentially threatening unit defeating this unit in combat.- Returns:
- A path to the threat, or null if not found.
-
isInDanger
public boolean isInDanger(int range, float threat)Checks if there is a credible threatening unit to this unit within a range of moves.- Parameters:
range- The number of turns to search for a threat within.threat- The maximum tolerable probability of a potentially threatening unit defeating this unit in combat.- Returns:
- True if a threat was found.
-
getLineOfSight
public int getLineOfSight()
Gets the line of sight of thisUnit. That is the distance thisUnitcan sight new tiles.- Returns:
- The line of sight of this
Unit.
-
getVisibleTileSet
public java.util.Set<Tile> getVisibleTileSet()
Get the tiles visible to this unit.- Returns:
- A set of visible
Tiles.
-
getGoodsInternal
private java.util.List<Goods> getGoodsInternal(boolean compact)
Get the goods carried by this unit.- Parameters:
compact- If true create a compact list.- Returns:
- A list of
Goods.
-
getGoodsList
public java.util.List<Goods> getGoodsList()
Get the goods carried by this unit.- Overrides:
getGoodsListin classGoodsLocation- Returns:
- A list of
Goods.
-
getCompactGoodsList
public java.util.List<Goods> getCompactGoodsList()
Get a compact version of the goods carried by this unit.- Overrides:
getCompactGoodsListin classGoodsLocation- Returns:
- A compact list of
Goods.
-
canCarryUnits
public boolean canCarryUnits()
Can this unit carry other units?- Returns:
- True if the unit can carry units.
-
couldCarry
public boolean couldCarry(Unit u)
Could this unit carry a specified one? This ignores the current load.- Parameters:
u- The potential cargoUnit.- Returns:
- True if this unit can carry the cargo.
-
canCarryGoods
public boolean canCarryGoods()
Can this unit carry goods.- Returns:
- True if the unit can carry goods.
-
couldCarry
public boolean couldCarry(Goods g)
Could this unit carry some specified goods? This ignores the current load.- Parameters:
g- The potential cargoGoods.- Returns:
- True if this unit can carry the cargo.
-
getSpaceLeft
public int getSpaceLeft()
Gets the number of free cargo slots left on this unit.- Returns:
- The number of free cargo slots on this unit.
-
hasSpaceLeft
public boolean hasSpaceLeft()
Is there free space left on this unit?- Returns:
- True if there is free space.
-
getCargoCapacity
public int getCargoCapacity()
Gets the total space this unit has to carry cargo.- Returns:
- The total space.
-
getGoodsSpaceTaken
public int getGoodsSpaceTaken()
Gets the space occupied by goods in this unit. Must defend against goods container being null as this can be called in the client on foreign units, which will not have goods containers.- Returns:
- The number cargo slots occupied by goods.
-
getUnitSpaceTaken
public int getUnitSpaceTaken()
Gets the space occupied by units in this unit.- Returns:
- The number of cargo slots occupied by units.
-
getCargoSpaceTaken
public int getCargoSpaceTaken()
Gets the space occupied by cargo in this unit (both goods and units).- Returns:
- The number of occupied cargo slots.
-
hasGoodsCargo
public boolean hasGoodsCargo()
Is this unit carrying any goods cargo?- Returns:
- True if the unit is carrying any goods cargo.
-
hasCargo
public boolean hasCargo()
Is this unit carrying any cargo (goods or unit).- Returns:
- True if the unit is carrying any cargo.
-
getLoadableAmount
public int getLoadableAmount(GoodsType type)
Gets the extra amount of a specified type of goods that could be loaded onto this unit. Includes empty cargo slots and any spare space in a slot partially filled with the specified goods.- Parameters:
type- TheGoodsTypeto examine.- Returns:
- The amount of goods that could be loaded onto this unit.
-
getOccupationLabel
public StringTemplate getOccupationLabel(Player player, boolean full)
Get a label for the current unit occupation.- Parameters:
player- ThePlayerviewing the unit, as the owner has access to more information.full- If true, return a more detailed result.- Returns:
- A
StringTemplatefor the unit occupation.
-
getConvertProbability
public float getConvertProbability()
Gets the probability that an attack by this unit will provoke a native to convert.- Returns:
- A probability of conversion.
-
getBurnProbability
public float getBurnProbability()
Gets the probability that an attack by this unit will provoke natives to burn our missions. FIXME: enhance burn probability proportionally with tension- Returns:
- A probability of burning missions.
-
canCashInTreasureTrain
public boolean canCashInTreasureTrain()
Checks if the treasure train can be cashed in at it's currentLocation.- Returns:
trueif the treasure train can be cashed in.- Throws:
java.lang.IllegalStateException- if this unit is not a treasure train.
-
canCashInTreasureTrain
public boolean canCashInTreasureTrain(Location loc)
Checks if the treasure train can be cashed in at the givenLocation.- Parameters:
loc- TheLocation.- Returns:
trueif the treasure train can be cashed in.- Throws:
java.lang.IllegalStateException- if this unit is not a treasure train.
-
getTransportFee
public int getTransportFee()
Get the fee that would have to be paid to transport this treasure to Europe.- Returns:
- The fee required for transport.
-
getSkillLevel
public int getSkillLevel()
Gets the skill level.- Returns:
- The level of skill for this unit. A higher value signals a more advanced type of units.
-
getUnitSkillLevel
public static int getUnitSkillLevel(UnitType unitType)
Gets the skill level of the given type ofUnit.- Parameters:
unitType- The type ofUnit.- Returns:
- The level of skill for the given unit. A higher value signals a more advanced type of units.
-
getMissionaryTradeModifiers
public java.util.Set<Modifier> getMissionaryTradeModifiers(boolean sense)
Gets the appropriate trade bonuses due to a missionary unit.- Parameters:
sense- The sense to apply the modifiers.- Returns:
- The missionary trade bonuses.
-
addFeature
public void addFeature(Feature feature)
Adds a feature to the Unit. This method always throws anUnsupportedOperationException, since features can not be added to Units directly.- Parameters:
feature- TheFeatureto add.
-
getProductionInfo
public ProductionInfo getProductionInfo(java.util.List<AbstractGoods> input)
Gets theProductionInfofor this unit. FIXME: the input parameter is ignored! Fix?- Parameters:
input- A list of inputAbstractGoods.- Returns:
- The
ProductionInfofor this unit.
-
getPioneerScore
public int getPioneerScore()
Score this unit with its suitability for pioneering. A pioneer must be a colonst. Favour: - existing pioneers especially if on the map - expert pioneer units - then by skill but not other experts- Returns:
- A pioneering score.
-
getScoutScore
public int getScoutScore()
Score this unit with its suitability for scouting. A scout must be a colonist. Favour: - existing scouts especially if on the map - expert scouts - lower skill level as scouting is a good career for crims and servants which might become seasoned scouts- Returns:
- A scouting score.
-
evaluateFor
public int evaluateFor(Player player)
Evaluate this unit for trade purposes.- Parameters:
player- ThePlayerto evaluate for.- Returns:
- A value of this unit.
-
getCombatModifiers
public java.util.Set<Modifier> getCombatModifiers(java.lang.String id, FreeColSpecObjectType fcgot, Turn turn)
Get modifiers required for combat. This can be replaced with just getModifiers() when accepted specifications have all combat modifiers with correct index values.- Parameters:
id- The identifier to get combat modifiers for.fcgot- An optionalFreeColSpecObjectTypethe modifier applies to.turn- An optional applicableTurn.- Returns:
- The set of
Modifiers found.
-
nonExpertWorker
private boolean nonExpertWorker(GoodsType work)
Is this unit a person that is making a given goods type, but not an expert at it.- Parameters:
work- TheGoodsTypeto check.- Returns:
- True if this unit is a non-expert worker.
-
trySwapExpert
public Unit trySwapExpert(java.util.List<Unit> others)
Try to swap this unit if it is an expert for another that is doing its job.- Parameters:
others- A list of otherUnits to test against.- Returns:
- The unit that was replaced by this expert, or null if none.
-
swapWork
public void swapWork(Unit other)
Swap work with another unit.- Parameters:
other- The otherUnit.
-
getNeighbourTile
public Tile getNeighbourTile(java.lang.String directionString)
Gets the tile in a given direction.- Parameters:
directionString- The direction.- Returns:
- The
Tilein the given direction. - Throws:
java.lang.IllegalStateException- if there is trouble.
-
getAdjacentSettlement
public <T extends Settlement> T getAdjacentSettlement(java.lang.String settlementId, java.lang.Class<T> returnClass)
Get a settlement by identifier, validating as much as possible. Designed for message unpacking where the identifier should not be trusted.- Type Parameters:
T- TheSettlementtype.- Parameters:
settlementId- The identifier of theSettlementto find.returnClass- The expected returned settlement class.- Returns:
- The settlement corresponding to the settlementId argument.
-
reduceVisibility
public Unit reduceVisibility(Tile tile, Player player)
Copy the unit, reduce visibility into any carrier and reference to a settlement. This is used when unit information is attached to an animation. The normal scope rules are inadequate there as the unit *must* be visible, but would normally be invisible if in a settlement or on a carrier.- Parameters:
tile- TheTilethe unit appears at.player- ThePlayerthe copy is for.- Returns:
- This
Unitwith reduced visibility.
-
getConsumedGoods
public java.util.List<AbstractGoods> getConsumedGoods()
Returns a list of GoodsTypes this Consumer consumes.- Specified by:
getConsumedGoodsin interfaceConsumer- Returns:
- a
Listvalue
-
getPriority
public int getPriority()
The priority of this Consumer. The higher the priority, the earlier will the Consumer be allowed to consume the goods it requires.- Specified by:
getPriorityin interfaceConsumer- Returns:
- an
intvalue
-
getConsumptionModifiers
public java.util.stream.Stream<Modifier> getConsumptionModifiers(java.lang.String id)
Get the modifier set with the given id. The modifier most relevant to consumers is "consumeOnlySurplusProduction", which implies that the consumer does not consume stored goods (used by the country and stables).- Specified by:
getConsumptionModifiersin interfaceConsumer- Parameters:
id- The object identifier.- Returns:
- The stream of
Modifiers found.
-
getOwner
public Player getOwner()
Gets the owner of thisOwnable.
-
setOwner
public void setOwner(Player player)
Sets the owner of thisOwnable. -vis: This routine has visibility implications.
-
getLocation
public Location getLocation()
Gets the location of this unit.- Specified by:
getLocationin interfaceLocatable- Returns:
- The location of this
Unit.
-
setLocation
public boolean setLocation(Location newLocation)
Sets the location of this unit. -vis: This routine changes player visibility. -til: While units do not contribute to tile appearance as such, if they move in/out of a colony the visible colony size changes.- Specified by:
setLocationin interfaceLocatable- Parameters:
newLocation- TheLocationwhere thisUnitis to be located.- Returns:
- True if the location change succeeds.
-
isInEurope
public boolean isInEurope()
Checks if thisUnitis located in Europe. That is; either directly or onboard a carrier which is in Europe.- Specified by:
isInEuropein interfaceLocatable- Returns:
- True if in
Europe.
-
getTile
public Tile getTile()
Gets the Tile associated with this Location.
-
getLocationLabel
public StringTemplate getLocationLabel()
Get a label for this location.- Specified by:
getLocationLabelin interfaceLocation- Overrides:
getLocationLabelin classUnitLocation- Returns:
- A label for this location.
-
add
public boolean add(Locatable locatable)
Adds aLocatableto this Location.- Specified by:
addin interfaceLocation- Overrides:
addin classGoodsLocation- Parameters:
locatable- TheLocatableto add to this Location.- Returns:
- True if the locatable was added.
-
remove
public boolean remove(Locatable locatable)
Removes aLocatablefrom this Location.- Specified by:
removein interfaceLocation- Overrides:
removein classGoodsLocation- Parameters:
locatable- TheLocatableto remove from this Location.- Returns:
- True if the locatable was removed.
-
getSettlement
public Settlement getSettlement()
Gets theSettlementthisLocationis located in.- Specified by:
getSettlementin interfaceLocation- Overrides:
getSettlementin classUnitLocation- Returns:
- The associated
Settlement, or null if none.
-
up
public Location up()
Promote this location to a more meaningful one if possible. For example: a settlement is more meaningful than the tile it occupies.
-
getRank
public int getRank()
Get a integer for this location, for the benefit of location comparators.
-
toShortString
public java.lang.String toShortString()
Get a short description of this location.- Specified by:
toShortStringin interfaceLocation- Returns:
- A short description.
-
getSpaceTaken
public int getSpaceTaken()
Gets the current space taken by the units in this location. Note that Units are also unit locations, but their space taken is derived from the spec, so this routine must be overrideable.- Specified by:
getSpaceTakenin interfaceLocatable- Overrides:
getSpaceTakenin classUnitLocation- Returns:
- The sum of the space taken by the units in this location.
-
getNoAddReason
public UnitLocation.NoAddReason getNoAddReason(Locatable locatable)
Gets the reason why a givenLocatablecan not be added to this Location. Be careful to test for unit presence last before success (NoAddReason.NONE) except perhaps for the capacity test, so that we can treat ALREADY_PRESENT as success in some cases (e.g. if the unit changes type --- does it still have a required skill?) FIXME: consider moving this up to Location?- Overrides:
getNoAddReasonin classGoodsLocation- Parameters:
locatable- TheLocatableto test.- Returns:
- The reason why adding would fail.
-
invalidateCache
public void invalidateCache()
Invalidate any cache dependent on the goods levels.- Specified by:
invalidateCachein classGoodsLocation
-
getGoodsCapacity
public int getGoodsCapacity()
Gets the maximum number ofGoodsthis Location can hold.- Specified by:
getGoodsCapacityin classGoodsLocation- Returns:
- The capacity for goods
-
disposeResources
public void disposeResources()
Dispose of the resources of this object, and finally remove it from the game. To be extended by subclasses, but they must tail call up towards this. -vis: This routine can change player visibility.- Overrides:
disposeResourcesin classUnitLocation
-
getLinkTarget
public FreeColGameObject getLinkTarget(Player player)
Get a suitable game object to use as a clickable link in messages to a player. Objects do not have links by default, hence the null return here. However, for example, a player's colony should return itself as a link target.- Overrides:
getLinkTargetin classFreeColGameObject- Parameters:
player- ThePlayerto make a link for.- Returns:
- A suitable link target if available, although usually null.
-
checkIntegrity
public Constants.IntegrityType checkIntegrity(boolean fix, LogBuilder lb)
Checks the integrity of this game object.- Overrides:
checkIntegrityin classFreeColGameObject- Parameters:
fix- If true, fix problems if possible.lb- ALogBuilderto log to.- Returns:
- A suitable
IntegrityType.
-
getAbilities
public java.util.stream.Stream<Ability> getAbilities(java.lang.String id, FreeColSpecObjectType fcgot, Turn turn)
Gets the set of abilities with the given identifier from this object. Subclasses with complex ability handling should override this as all prior routines are derived from it.- Overrides:
getAbilitiesin classFreeColObject- Parameters:
id- The object identifier.fcgot- An optionalFreeColSpecObjectTypethe ability applies to.turn- An optional applicableTurn.- Returns:
- A set of abilities.
-
getLocationAbilities
private java.util.stream.Stream<Ability> getLocationAbilities(java.lang.String id, Turn turn)
Get abilities specific to this location. This is here just to simplify getAbilities(). Perhaps one day it could be wrapped back in, but there is unresolved complexity. FIXME: extend this to all locations? May simplify code. Units are also Locations however, which complicates the issue as we do not want Units aboard other Units to share the abilities of the carriers.- Parameters:
id- The identifier to check.turn- The turn that applies.- Returns:
- A stream of
Abilitys found.
-
getModifiers
public java.util.stream.Stream<Modifier> getModifiers(java.lang.String id, FreeColSpecObjectType fcgot, Turn turn)
Gets the set of modifiers with the given identifier from this object. Subclasses with complex modifier handling may override this routine.- Overrides:
getModifiersin classFreeColObject- Parameters:
id- The object identifier.fcgot- An optionalFreeColSpecObjectTypethe modifier applies to.turn- An optional applicableTurn.- Returns:
- A set of modifiers.
-
getClassIndex
public int getClassIndex()
Accessor for the class index.- Overrides:
getClassIndexin classFreeColGameObject- Returns:
- The class index used by
ClientOptions.
-
copyIn
public <T extends FreeColObject> boolean copyIn(T other)
Copy another FreeColObject into this one if it is compatible.- Overrides:
copyInin classGoodsLocation- Type Parameters:
T- TheFreeColObjectsubclass of the object to copy in.- Parameters:
other- The other object.- Returns:
- True if the copy in is succesful.
-
getDisplayObject
public FreeColObject getDisplayObject()
Get an object to display when showing the user messages for this object. Example: If this object is a Building, the object to display will be the BuildingType.- Overrides:
getDisplayObjectin classFreeColObject- Returns:
- A suitable
FreeColObjectto display, defaults to this.
-
writeAttributes
protected void writeAttributes(FreeColXMLWriter xw) throws javax.xml.stream.XMLStreamException
Write the attributes of this object to a stream. To be overridden if required by any object that has attributes and uses the toXML(FreeColXMLWriter, String) call.- Overrides:
writeAttributesin classFreeColObject- Parameters:
xw- TheFreeColXMLWriterto write to.- Throws:
javax.xml.stream.XMLStreamException- if there are any problems writing to the stream.
-
writeChildren
protected void writeChildren(FreeColXMLWriter xw) throws javax.xml.stream.XMLStreamException
Write the children of this object to a stream. To be overridden if required by any object that has children and uses the toXML(FreeColXMLWriter, String) call.- Overrides:
writeChildrenin classGoodsLocation- Parameters:
xw- TheFreeColXMLWriterto write to.- Throws:
javax.xml.stream.XMLStreamException- if there are any problems writing to the stream.
-
readAttributes
protected void readAttributes(FreeColXMLReader xr) throws javax.xml.stream.XMLStreamException
Reads the attributes of this object from an XML stream.- Overrides:
readAttributesin classFreeColGameObject- Parameters:
xr- TheFreeColXMLReaderto read from.- Throws:
javax.xml.stream.XMLStreamException- if there is a problem reading the stream.
-
readChildren
protected void readChildren(FreeColXMLReader xr) throws javax.xml.stream.XMLStreamException
Reads the children of this object from an XML stream.- Overrides:
readChildrenin classGoodsLocation- Parameters:
xr- TheFreeColXMLReaderto read from.- Throws:
javax.xml.stream.XMLStreamException- if there is a problem reading the stream.
-
readChild
protected void readChild(FreeColXMLReader xr) throws javax.xml.stream.XMLStreamException
Reads a single child object. Subclasses must override to read their enclosed elements. This particular instance of the routine always throws XMLStreamException because we should never arrive here. However it is very useful to always call super.readChild() when an unexpected tag is encountered, as the exception thrown here provides some useful debugging context.- Overrides:
readChildin classGoodsLocation- Parameters:
xr- TheFreeColXMLReaderto read from.- Throws:
javax.xml.stream.XMLStreamException- if there is a problem reading the stream.
-
getXMLTagName
public java.lang.String getXMLTagName()
Get the serialization tag for this object.- Specified by:
getXMLTagNamein classFreeColObject- Returns:
- The tag.
-
toString
public java.lang.String toString()
- Overrides:
toStringin classFreeColObject
-
toString
public java.lang.String toString(java.lang.String prefix)
Gets a string representation of this unit.- Parameters:
prefix- A prefix (e.g. "AIUnit")- Returns:
- A string representation of this
Unit.
-
-