Package net.sf.freecol.server.ai
Class AIUnit
- java.lang.Object
-
- All Implemented Interfaces:
java.lang.Comparable<FreeColObject>,ObjectWithId
public final class AIUnit extends TransportableAIObject
Objects of this class contains AI-information for a singleUnit. AIUnits are successfully initialized by a call tosetUnit(Unit)with a non-null actualUnit. The methoddoMission(LogBuilder)is called once each turn, byAIPlayer.startWorking(), to perform the assignedMission. Most of the methods in this class just delegates the call to that mission.- See Also:
Mission
-
-
Field Summary
Fields Modifier and Type Field Description private static java.util.logging.Loggerloggerprivate MissionmissionThe mission to which this AI unit has been assigned.static java.lang.StringTAGprivate UnitunitThe Unit this AIObject contains AI-information for.-
Fields inherited from class net.sf.freecol.server.ai.TransportableAIObject
FULL_DELIVERY, IMPORTANT_DELIVERY, TOOLS_FOR_BUILDING, TOOLS_FOR_COLONY_PRIORITY, TOOLS_FOR_IMPROVEMENT, TOOLS_FOR_PIONEER
-
Fields inherited from class net.sf.freecol.server.ai.ValuedAIObject
ascendingValueComparator, descendingValueComparator
-
Fields inherited from class net.sf.freecol.server.ai.AIObject
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
-
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description booleancanMove()This transportable can move now.booleancarriableBy(Unit carrier)Can this transportable be carried by a given carrier unit?MissionchangeMission(Mission mission)Change the mission of a unit.Constants.IntegrityTypecheckIntegrity(boolean fix, LogBuilder lb)AIObjects need integrity checking too.voiddispose()Disposes this object and any attached mission.voiddoMission(LogBuilder lb)Performs the mission this unit has been assigned.booleanequals(java.lang.Object o)booleanequipForRole(Role role)Equips this AI unit for a particular role.AIPlayergetAIOwner()Gets the AIPlayer that owns this AIUnit.java.util.RandomgetAIRandom()Gets the PRNG to use with this unit.intgetBuilderScore()Score this AI unit with its suitability for building.PathNodegetDeliveryPath(Unit carrier, Location dst)Get the path to deliver this transportable to its destination with a given carrier.PathNodegetIntermediatePath(Unit carrier, Location dst)Get the path to make progress with this transport, for the carrier to either collect or deliver the transportable, albeit it need only improve the current situation rather than complete the delivery to the destination.MissiongetMission()Gets the mission this unit has been assigned.<T extends Mission>
TgetMission(java.lang.Class<T> returnClass)Get the unit mission if it is of a given class.PlayergetOwner()Get thePlayerthat owns this AIUnit.intgetPioneerScore()Score this AI unit with its suitability for pioneering.intgetScoutScore()Score this AI unit with its suitability for scouting.LocationgetTransportDestination()Get the destination location for this transportable AI object.LocatablegetTransportLocatable()Gets the underlying locatable object which should be transported.intgetTransportPriority()Gets the priority of transporting this object to its destination.LocationgetTransportSource()Get the source location for this transportable AI object.LocationgetTrivialTarget()Get a trivial target, usually a safe nearby settlement or Europe.UnitgetUnit()Gets theUnitthisAIUnitcontrols.java.lang.StringgetXMLTagName()Get the serialization tag for this object.booleanhasCargo()Is this AI unit carrying any cargo (units or goods).booleanhasDefendSettlementMission()inthashCode()booleanhasMission()Checks if this unit has been assigned a mission.<T extends Mission>
booleanhasMission(java.lang.Class<T> returnClass)Does this unit have a particular class of mission?java.lang.StringinvalidReason()Is there a reason to invalidate transporting this object?booleanisAvailableForWork(Colony colony)booleanisCompleteWishRealizationMission(Colony colony)booleanjoinTransport(Unit carrier, Direction direction)This object joins a carrier unit.booleanleaveTransport()This object leaves its current carrier unit by the most suitable means.booleanleaveTransport(Direction direction)This object leaves its current carrier unit.booleanmove(Direction direction)Moves this AI unit.booleanmoveToAmerica()Moves a unit to the new world.booleanmoveToEurope()Moves a unit to Europe.protected voidreadAttributes(FreeColXMLReader xr)Reads the attributes of this object from an XML stream.protected voidreadChild(FreeColXMLReader xr)Reads a single child object.voidremoveMission()voidremoveTransportable(AIGoods ag)private voidrequestLocalRearrange()Request a rearrangement of any colony at the current location.voidsetInitialized()Set the initialized flag in this object.voidsetMission(Mission mission)Assigns a mission to unit.voidsetTransportDestination(Location destination)Set the destination location for this transportable AI object.private voidsetUnit(Unit unit)Set theUnitthisAIUnitcontrols.private voidtakeTransport()Take the current carrier as transport, keeping the transport mission/s consistent.java.lang.StringtoString()booleantryPioneeringMission(LogBuilder lb)booleantrySomeUsefulMission(Colony colony, LogBuilder lb)booleantryWorkInsideColonyMission(AIColony aiColony, LogBuilder lb)protected voidwriteChildren(FreeColXMLWriter xw)Write the children of this object to a stream.-
Methods inherited from class net.sf.freecol.server.ai.TransportableAIObject
changeTransport, dropTransport, getLocation, getSpaceTaken, getTransport, incrementTransportPriority, setTransport, setTransportPriority, writeAttributes
-
Methods inherited from class net.sf.freecol.server.ai.ValuedAIObject
getValue, setValue
-
Methods inherited from class net.sf.freecol.server.ai.AIObject
addAIObjectWithId, checkIntegrity, copyIn, getAIMain, getGame, getSpecification, isDisposed, 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, getAbilities, getClassIndex, getDefenceModifiers, getDisplayObject, getFeatureContainer, getFreeColObjectClass, getFreeColObjectClassByName, getId, getIdNumber, getIdType, getIdTypeByName, getModifiers, getModifiers, getModifiers, getModifiers, getObjectClassIndex, getPropertyChangeListeners, getPropertyChangeListeners, getPropertyChangeSupport, getSortedAbilities, getSortedModifiers, getSuffix, getSuffix, hasAbility, hasAbility, hasAbility, hasListeners, hasModifier, hasModifier, hasModifier, idEquals, invokeMethod, logFreeColObjects, readChildren, readFromXML, readFromXMLPartial, removeAbilities, removeAbility, removeFeatures, removeModifier, removeModifiers, removePropertyChangeListener, removePropertyChangeListener, save, save, save, save, serialize, serialize, serialize, serialize, setId, toXML, toXML, toXMLPartial, toXMLPartial
-
-
-
-
Field Detail
-
logger
private static final java.util.logging.Logger logger
-
TAG
public static final java.lang.String TAG
- See Also:
- Constant Field Values
-
unit
private Unit unit
The Unit this AIObject contains AI-information for.
-
mission
private Mission mission
The mission to which this AI unit has been assigned.
-
-
Constructor Detail
-
AIUnit
public AIUnit(AIMain aiMain, java.lang.String id)
Creates a new uninitializedAIUnit.- Parameters:
aiMain- The main AI-object.id- The object identifier.
-
AIUnit
public AIUnit(AIMain aiMain, Unit unit)
Creates a newAIUnit.- Parameters:
aiMain- The main AI-object.unit- The unit to make anAIObjectfor.
-
AIUnit
public AIUnit(AIMain aiMain, FreeColXMLReader xr) throws javax.xml.stream.XMLStreamException
Creates a newAIUnitfrom the given XML-representation.- Parameters:
aiMain- The main AI-object.xr- The input stream containing the XML.- Throws:
javax.xml.stream.XMLStreamException- if a problem was encountered during parsing.
-
-
Method Detail
-
setInitialized
public void setInitialized()
Set the initialized flag in this object. To be implemented by leaf classes, and called in their constructors plus the special case in readChild below where we resolve forward references.- Specified by:
setInitializedin classAIObject
-
getUnit
public final Unit getUnit()
Gets theUnitthisAIUnitcontrols.- Returns:
- The
Unit.
-
setUnit
private final void setUnit(Unit unit)
Set theUnitthisAIUnitcontrols. Note: it is an error to change the unit once it is set.- Parameters:
unit- The newUnit.
-
hasMission
public final boolean hasMission()
Checks if this unit has been assigned a mission.- Returns:
- True if this unit has a mission.
-
getMission
public final Mission getMission()
Gets the mission this unit has been assigned.- Returns:
- The
Mission.
-
setMission
public final void setMission(Mission mission)
Assigns a mission to unit.- Parameters:
mission- The newMission.
-
requestLocalRearrange
private void requestLocalRearrange()
Request a rearrangement of any colony at the current location.
-
takeTransport
private void takeTransport()
Take the current carrier as transport, keeping the transport mission/s consistent.
-
getOwner
public Player getOwner()
Get thePlayerthat owns this AIUnit.- Returns:
- The owning
Player.
-
getAIOwner
public AIPlayer getAIOwner()
Gets the AIPlayer that owns this AIUnit.- Returns:
- The owning AIPlayer.
-
getAIRandom
public java.util.Random getAIRandom()
Gets the PRNG to use with this unit.- Returns:
- A
Randominstance.
-
getTrivialTarget
public Location getTrivialTarget()
Get a trivial target, usually a safe nearby settlement or Europe.- Returns:
- A trivial target, or null if none found.
-
hasCargo
public final boolean hasCargo()
Is this AI unit carrying any cargo (units or goods).- Returns:
- True if the unit has cargo aboard.
-
hasMission
public <T extends Mission> boolean hasMission(java.lang.Class<T> returnClass)
Does this unit have a particular class of mission?- Type Parameters:
T- The type of the mission.- Parameters:
returnClass- TheClassof mission to check.- Returns:
- True if the mission is of the given class.
-
getMission
public <T extends Mission> T getMission(java.lang.Class<T> returnClass)
Get the unit mission if it is of a given class.- Type Parameters:
T- The type of the mission.- Parameters:
returnClass- TheClassof the mission.- Returns:
- The
Mission, or null if it is not of the given class.
-
doMission
public void doMission(LogBuilder lb)
Performs the mission this unit has been assigned. Do *not* check mission validity. The mission itself does that, and has special case error handling.- Parameters:
lb- ALogBuilderto log to.
-
changeMission
public Mission changeMission(Mission mission)
Change the mission of a unit.- Parameters:
mission- The newMission.- Returns:
- The new current
Mission.
-
removeMission
public void removeMission()
-
hasDefendSettlementMission
public boolean hasDefendSettlementMission()
-
isCompleteWishRealizationMission
public boolean isCompleteWishRealizationMission(Colony colony)
-
isAvailableForWork
public boolean isAvailableForWork(Colony colony)
-
tryWorkInsideColonyMission
public boolean tryWorkInsideColonyMission(AIColony aiColony, LogBuilder lb)
-
tryPioneeringMission
public boolean tryPioneeringMission(LogBuilder lb)
-
trySomeUsefulMission
public boolean trySomeUsefulMission(Colony colony, LogBuilder lb)
-
removeTransportable
public void removeTransportable(AIGoods ag)
-
moveToAmerica
public boolean moveToAmerica()
Moves a unit to the new world.- Returns:
- True if there was no c-s problem.
-
moveToEurope
public boolean moveToEurope()
Moves a unit to Europe.- Returns:
- True if there was no c-s problem.
-
move
public boolean move(Direction direction)
Moves this AI unit.- Parameters:
direction- TheDirectionto move.- Returns:
- True if the move succeeded.
-
equipForRole
public boolean equipForRole(Role role)
Equips this AI unit for a particular role. The unit must be at a location where the required goods are available (possibly requiring a purchase, which may fail due to lack of gold or boycotts in effect).- Parameters:
role- TheRoleto equip for identifier.- Returns:
- True if the role change was successful.
-
getBuilderScore
public int getBuilderScore()
Score this AI unit with its suitability for building. Favour unequipped freeColonists, and other unskilled over experts. Also slightly favour units on the map.- Returns:
- An integer score.
-
getPioneerScore
public int getPioneerScore()
Score this AI unit with its suitability for pioneering.- Returns:
- An integer score.
-
getScoutScore
public int getScoutScore()
Score this AI unit with its suitability for scouting.- Returns:
- An integer score.
-
getTransportPriority
public int getTransportPriority()
Gets the priority of transporting this object to its destination.- Overrides:
getTransportPriorityin classTransportableAIObject- Returns:
- The priority of the transport.
-
getTransportLocatable
public Locatable getTransportLocatable()
Gets the underlying locatable object which should be transported.- Specified by:
getTransportLocatablein classTransportableAIObject- Returns:
- The
Locatable.
-
getTransportSource
public Location getTransportSource()
Get the source location for this transportable AI object. This is normally the location of thelocatable.- Specified by:
getTransportSourcein classTransportableAIObject- Returns:
- The source
Location.
-
getTransportDestination
public Location getTransportDestination()
Get the destination location for this transportable AI object. This can be the targetTileof the transport or the target of the mission.- Specified by:
getTransportDestinationin classTransportableAIObject- Returns:
- The destination
Location.
-
getDeliveryPath
public PathNode getDeliveryPath(Unit carrier, Location dst)
Get the path to deliver this transportable to its destination with a given carrier.- Specified by:
getDeliveryPathin classTransportableAIObject- Parameters:
carrier- The carrierUnitto use.dst- The destinationLocation, defaulting to the transport destination if null.- Returns:
- A path, or null if none found.
-
getIntermediatePath
public PathNode getIntermediatePath(Unit carrier, Location dst)
Get the path to make progress with this transport, for the carrier to either collect or deliver the transportable, albeit it need only improve the current situation rather than complete the delivery to the destination.- Specified by:
getIntermediatePathin classTransportableAIObject- Parameters:
carrier- The carrierUnitto use.dst- The destinationLocation, defaulting to the transport destination if null.- Returns:
- A path, or null if none found.
-
setTransportDestination
public void setTransportDestination(Location destination)
Set the destination location for this transportable AI object.- Specified by:
setTransportDestinationin classTransportableAIObject- Parameters:
destination- The destinationLocation.
-
carriableBy
public boolean carriableBy(Unit carrier)
Can this transportable be carried by a given carrier unit?- Specified by:
carriableByin classTransportableAIObject- Parameters:
carrier- The potential carrierUnit.- Returns:
- True if the unit can carry this transportable.
-
canMove
public boolean canMove()
This transportable can move now. Useful for units that may or may not have enough moves left to join or leave a carrier.- Specified by:
canMovein classTransportableAIObject- Returns:
- True if the transportable can move.
-
leaveTransport
public boolean leaveTransport()
This object leaves its current carrier unit by the most suitable means.- Specified by:
leaveTransportin classTransportableAIObject- Returns:
- True if the object successfully left the carrier.
-
leaveTransport
public boolean leaveTransport(Direction direction)
This object leaves its current carrier unit.- Specified by:
leaveTransportin classTransportableAIObject- Parameters:
direction- TheDirectionto leave in, null to leave in place.- Returns:
- True if the object successfully left the carrier.
-
joinTransport
public boolean joinTransport(Unit carrier, Direction direction)
This object joins a carrier unit.- Specified by:
joinTransportin classTransportableAIObject- Parameters:
carrier- The carrierUnitto join.direction- TheDirectionto move, null to join a carrier in the same location.- Returns:
- True if the object has joined tha carrier.
-
invalidReason
public java.lang.String invalidReason()
Is there a reason to invalidate transporting this object?- Specified by:
invalidReasonin classTransportableAIObject- Returns:
- A reason to abort transport, or null if none found.
-
dispose
public void dispose()
Disposes this object and any attached mission.
-
checkIntegrity
public Constants.IntegrityType checkIntegrity(boolean fix, LogBuilder lb)
AIObjects need integrity checking too.- Overrides:
checkIntegrityin classAIObject- Parameters:
fix- If true, fix problems if possible.lb- ALogBuilderto log to.- Returns:
- -1 if there are problems remaining, zero if problems were fixed, +1 if no problems found at all.
-
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 classFreeColObject- 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 classTransportableAIObject- 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 classFreeColObject- 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.
-
equals
public boolean equals(java.lang.Object o)
- Overrides:
equalsin classTransportableAIObject
-
hashCode
public int hashCode()
- Overrides:
hashCodein classTransportableAIObject
-
toString
public java.lang.String toString()
- Overrides:
toStringin classFreeColObject
-
-