net.sf.freecol.server.ai.goal
Class Goal

java.lang.Object
  extended by net.sf.freecol.common.model.FreeColObject
      extended by net.sf.freecol.server.ai.AIObject
          extended by net.sf.freecol.server.ai.goal.Goal
All Implemented Interfaces:
GoalConstants
Direct Known Subclasses:
CreateMissionAtSettlementGoal, GotoAdjacentGoal, ManageMissionariesGoal

public abstract class Goal
extends AIObject
implements GoalConstants

A Goal is used to encapsulate a specific part of the decision-making process of an AI.

Using a top-down approach, every AIPlayer has a set of Goals which, in turn, may have further subgoals. In combination, this tree of goals and subgoals reflects the current strategy of the AIPlayer.

Units (each one wrapped in an AIUnit object) will be moved between existing Goal objects. TODO: Turn AIUnit into a simple wrapper for individual units.

Specific AI goals are created by extending this class; some of these could also be used to assist the human player (i.e. GoTo, Scouting, Trade, Piracy).


Field Summary
protected  java.util.List<AIUnit> availableUnitsList
           
protected  boolean isFinished
           
private static java.util.logging.Logger logger
           
protected  boolean needsPlanning
           
private  Goal parentGoal
           
protected  AIPlayer player
           
private  float relativeWeight
           
private  int turnCreated
           
private  int turnLastUnitAdded
           
 
Fields inherited from class net.sf.freecol.server.ai.AIObject
uninitialized
 
Fields inherited from class net.sf.freecol.common.model.FreeColObject
ARRAY_SIZE, ID_ATTRIBUTE, ID_ATTRIBUTE_TAG, PARTIAL_ATTRIBUTE
 
Fields inherited from interface net.sf.freecol.server.ai.goal.GoalConstants
MAX_SEARCH_RADIUS
 
Constructor Summary
Goal(AIPlayer p, Goal g, float w)
          Standard constructor
Goal(AIPlayer p, Goal g, float w, AIUnit u)
          Alternate constructor - directly add a unit to this Goal.
 
Method Summary
 void addUnit(AIUnit u)
          Adds a unit to this goal.
protected  void addUnitToParent(AIUnit u)
          Adds a unit to the parent goal.
 java.util.List<AIUnit> cancelGoal()
          Cancels a goal and all of its subgoals.
 boolean canYieldUnit(UnitType ut, AIObject o)
          Used by a parent goal to check whether this goal, including subgoals, can yield a specific unit.
 void doPlanning()
          Recursively calls doPlanning() in subgoals that needsPlanning(), then calls its own planning method.
 float getAbsoluteWeight()
          Returns the absolute weight of this goal.
 java.lang.String getDebugDescription()
          Build and return a string describing this goal including its parent goal.
 java.lang.String getGoalDescription()
          Returns a string describing just this goal.
protected abstract  java.util.Iterator<AIUnit> getOwnedAIUnitsIterator()
          Since internal implementation details may vary, each Goal will define an iterator over all of its units.
 float getParentWeight()
          Gets the weight of the parent goal, or 1 if there is no parent goal.
protected abstract  java.util.Iterator<Goal> getSubGoalIterator()
          Since internal implementation details may vary, each Goal will define an iterator over all of its subgoals.
 float getWeight()
          Returns the relativeWeight this goal has been weighted with by its parent.
static java.lang.String getXMLElementTagName()
          Returns the tag name of the root element representing this object.
 float getYieldedUnitWeight(UnitType ut, AIObject o)
          Returns the absolute weight of the unit which would be yielded by yieldUnit(UnitType,AIObject).
 boolean isFinished()
          Determines whether this goal is finished.
 boolean needsPlanning()
          Determines whether this or a subgoal needsPlanning.
 void normalizeSubGoalWeights()
          Calling this ensures that the relative weights given to subgoals add up to 1.
protected abstract  void plan()
          This is the method that actually does the planning for this goal.
protected abstract  void readFromXMLImpl(javax.xml.stream.XMLStreamReader in)
          Reads information for this object from an XML stream.
protected abstract  void removeUnit(AIUnit u)
          Ensures that a unit moved to another Goal is properly removed from this.
protected  void requestWorker(GoodsType gt, int minProduction)
          Wrapper method for a worker request sent to the AIPlayer.
 void setNeedsPlanningRecursive(boolean p)
          Sets the needsPlanning status of this Goal and all its subgoals.
 void setWeight(float w)
          Sets a relative weight for this goal.
protected abstract  void toXMLImpl(javax.xml.stream.XMLStreamWriter out)
          Writes this object to an XML stream.
protected  void validateOwnedUnits()
          Checks all owned AIUnits for validity, and removes invalid ones.
 AIUnit yieldUnit(UnitType ut, AIObject o)
          Removes a unit from the goal, potentially from a subgoal, and yields it to the caller.
 
Methods inherited from class net.sf.freecol.server.ai.AIObject
dispose, getAIMain, getAIRandom, getGame, isUninitialized, readFromXML
 
Methods inherited from class net.sf.freecol.common.model.FreeColObject
addPropertyChangeListener, addPropertyChangeListener, fireIndexedPropertyChange, fireIndexedPropertyChange, fireIndexedPropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getAttribute, getAttribute, getAttribute, getAttribute, getId, getPropertyChangeListeners, getPropertyChangeListeners, hasAbility, hasAttribute, hasListeners, readAttributes, readChildren, readFromArrayElement, readFromArrayElement, readFromArrayElement, readFromListElement, readFromXMLElement, readFromXMLPartialImpl, removePropertyChangeListener, removePropertyChangeListener, setId, toArrayElement, toArrayElement, toListElement, toXML, toXML, toXML, toXMLElement, toXMLElement, toXMLElement, toXMLElement, toXMLElementPartial, toXMLPartialImpl, writeAttribute, writeAttributes, writeChildren, writeFreeColGameObject
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

logger

private static final java.util.logging.Logger logger

relativeWeight

private float relativeWeight

turnCreated

private int turnCreated

turnLastUnitAdded

private int turnLastUnitAdded

needsPlanning

protected boolean needsPlanning

isFinished

protected boolean isFinished

availableUnitsList

protected java.util.List<AIUnit> availableUnitsList

player

protected AIPlayer player

parentGoal

private Goal parentGoal
Constructor Detail

Goal

public Goal(AIPlayer p,
            Goal g,
            float w)
Standard constructor

Parameters:
p - The AIPlayer this goal belongs to
g - The parent goal; may be null if we're a direct goal of the AIPlayer
w - The relativeWeight of this goal

Goal

public Goal(AIPlayer p,
            Goal g,
            float w,
            AIUnit u)
Alternate constructor - directly add a unit to this Goal. The calling object ensures that this unit is not currently part of another Goal.

Parameters:
p - The AIPlayer this goal belongs to
g - The parent goal; may be null if we're a direct goal of the AIPlayer
w - The relativeWeight of this goal
u - An initial AIUnit given to this goal
Method Detail

isFinished

public boolean isFinished()
Determines whether this goal is finished. If it is, this means it can be cancelled by its parent.

Returns:
true, if the goal is finished, false otherwise

cancelGoal

public java.util.List<AIUnit> cancelGoal()
Cancels a goal and all of its subgoals. If a goal is cancelled, it will recursively cancelGoal() its subgoals first, and return all units to the object calling this. After this method has been called, it should be safe for the parent to remove this goal from its list of subgoals.

NOTE: Preferably, only the direct parent should call this.

Returns:
A list of all AIUnit being freed up by this action

doPlanning

public void doPlanning()
Recursively calls doPlanning() in subgoals that needsPlanning(), then calls its own planning method.


needsPlanning

public boolean needsPlanning()
Determines whether this or a subgoal needsPlanning.

Returns:
true if this Goal or at least one subgoal needs planning, false otherwise

setNeedsPlanningRecursive

public void setNeedsPlanningRecursive(boolean p)
Sets the needsPlanning status of this Goal and all its subgoals. Should be called by the AIPlayer once for each of its subgoals at the start of a turn. The Goal will handle all other instances of this flag needing to be reset internally.

Parameters:
p - Boolean determining whether to set needsPlanning =true or =false

getWeight

public float getWeight()
Returns the relativeWeight this goal has been weighted with by its parent.

NOTE: In many cases, you will want to use getAbsoluteWeight() instead.

Returns:
The relative weight relativeWeight of this goal

getParentWeight

public float getParentWeight()
Gets the weight of the parent goal, or 1 if there is no parent goal.

Returns:
The absolute weight [0;1] of the parent goal, or 1 if a parent goal does not exist

getAbsoluteWeight

public float getAbsoluteWeight()
Returns the absolute weight of this goal.

The absolute weight is the weight of this goal in relation to the AIPlayer. This is used when making requests, to allow the AIPlayer to find the "most important" request.

Returns:
The absolute weight [0;1] of this goal

setWeight

public void setWeight(float w)
Sets a relative weight for this goal. Each Goal is weighted by its parent goal. The parent should assure that the sum of weights given to its subgoals is =1

Parameters:
w - A relative weight, should be in range [0;1]

normalizeSubGoalWeights

public void normalizeSubGoalWeights()
Calling this ensures that the relative weights given to subgoals add up to 1.

NOTE: This allows for a small margin of error (+/- 0.05), to avoid recalculating too often.


requestWorker

protected void requestWorker(GoodsType gt,
                             int minProduction)
Wrapper method for a worker request sent to the AIPlayer.

Each Goal can request necessary units from the AIPlayer. Here, such a request is wrapped in a private method for convenience. Each request contains a weight, which is getAbsoluteWeight() of this goal, and the number of turns since a unit request has last been granted. The latter should be taken into account as a "bonus weight" by the AIPlayer.

TODO: AIPlayer#addUnitWish(Goal,GoodsType,int,float,int); should add requests to a set-like structure, so that there's only one active request per Goal at any time. Since fulfilling a request using addUnit(AIUnit) means that plan() will be called again during the turn, the Goal will be able to request again.

Parameters:
gt - The GoodsType we're requesting a worker for.
minProduction - The minimum a unit needs to produce to be considered. Should be 0 if any worker will do, or the value of UnitType.getProductionFor(GoodsType,int) if an existing worker unit is supposed to be replaced.

addUnit

public void addUnit(AIUnit u)
Adds a unit to this goal. This may be from AIPlayer fulfilling a unit request, by the parent goal, or by a subgoal that no longer needs the unit.

Possible TODO: If the unit we're requesting is a high-interest one, such as a Galleon, AIUnit#setLoaningGoal() may be used to signal that this unit may _only_ be moved to subgoals, or back to AIPlayer, but not further up the hierarchy or to any other requesting Goal.

Parameters:
u - The AIUnit being added to this goal

addUnitToParent

protected void addUnitToParent(AIUnit u)
Adds a unit to the parent goal. If this goal doesn't have a parent goal, the unit will be added to AIPlayer instead.

Parameters:
u - The AIUnit to be added to the parent

canYieldUnit

public boolean canYieldUnit(UnitType ut,
                            AIObject o)
Used by a parent goal to check whether this goal, including subgoals, can yield a specific unit.

This recursively checks its subgoals, if there's no match among the own units.

Possible TODO: Check whether AIUnit#isOnLoan() - in which case, we mustn't yield a unit unless it's the AIPlayer that requests.

Parameters:
ut - The UnitType wanted by the parent
o - The AIObject (should be AIPlayer or another Goal) calling this
Returns:
true if this goal or one of its subgoals can yield the specified UnitType, false otherwise

getYieldedUnitWeight

public float getYieldedUnitWeight(UnitType ut,
                                  AIObject o)
Returns the absolute weight of the unit which would be yielded by yieldUnit(UnitType,AIObject). This is the same as getAbsoluteWeight() of the yielding goal.

Parameters:
ut - The UnitType wanted by the parent
o - The AIObject (should be AIPlayer or another Goal) calling this
Returns:
The absolute weight ([0;1]) of the goal currently owning the unit that would be yielded. Note that the returned value might be 99f if there is no unit to yield. The calling function should use canYieldUnit(UnitType,AIObject) first, or is responsible to sanitize this result itself before trying to yieldUnit(UnitType,AIObject) based on it.

yieldUnit

public AIUnit yieldUnit(UnitType ut,
                        AIObject o)
Removes a unit from the goal, potentially from a subgoal, and yields it to the caller.

Returned unit should be the one with minimum absolute weight, see getYieldedUnitWeight(UnitType,AIObject).

Parameters:
ut - The UnitType wanted by the parent
o - The AIObject (should be AIPlayer or another Goal) calling this
Returns:
The AIUnit with minimal absolute weight. Note that this may be null if no matching unit is found!

validateOwnedUnits

protected void validateOwnedUnits()
Checks all owned AIUnits for validity, and removes invalid ones. An AIUnit is supposed to be invalid if it no longer contains a valid Unit. This may be the case if the Unit has been removed from the game between turns.

NOTE: The assumption here is that AIUnit#isValid() will return true as long as the Unit wrapped in it exists.


getGoalDescription

public java.lang.String getGoalDescription()
Returns a string describing just this goal. An implementing class may override this method to add specialized information. Used by getDebugDescription.

Returns:
a string describing this goal

getDebugDescription

public java.lang.String getDebugDescription()
Build and return a string describing this goal including its parent goal. Used by "Display AI-missions" in debug mode.

Returns:
a string describing this goal

getXMLElementTagName

public static java.lang.String getXMLElementTagName()
Returns the tag name of the root element representing this object.

Returns:
"aiGoal"

getOwnedAIUnitsIterator

protected abstract java.util.Iterator<AIUnit> getOwnedAIUnitsIterator()
Since internal implementation details may vary, each Goal will define an iterator over all of its units.

Returns:
An Iterator over all AIUnit currently managed by this goal.

getSubGoalIterator

protected abstract java.util.Iterator<Goal> getSubGoalIterator()
Since internal implementation details may vary, each Goal will define an iterator over all of its subgoals.

Returns:
An Iterator over all currently existing subgoals.

removeUnit

protected abstract void removeUnit(AIUnit u)
Ensures that a unit moved to another Goal is properly removed from this. If a unit is removed from this goal via yieldUnit(UnitType,AIObject), or if the Unit contained in the AIUnit no longer is valid, this method is called to clean up any remaining references to the unit.

Any implementation of this will need to iterate over all AIUnit object references used by this goal, and remove those that equal the given parameter.

Parameters:
u - The AIUnit supposed to be removed from this goal.

plan

protected abstract void plan()
This is the method that actually does the planning for this goal. It should contain:


toXMLImpl

protected abstract void toXMLImpl(javax.xml.stream.XMLStreamWriter out)
                           throws javax.xml.stream.XMLStreamException
Writes this object to an XML stream.

Specified by:
toXMLImpl in class FreeColObject
Parameters:
out - The target stream.
Throws:
javax.xml.stream.XMLStreamException - if there are any problems writing to the stream.

readFromXMLImpl

protected abstract void readFromXMLImpl(javax.xml.stream.XMLStreamReader in)
                                 throws javax.xml.stream.XMLStreamException
Reads information for this object from an XML stream.

Overrides:
readFromXMLImpl in class FreeColObject
Parameters:
in - The input stream with the XML.
Throws:
javax.xml.stream.XMLStreamException - if there are any problems reading from the stream.