net.sf.freecol.common.model
Class Map

java.lang.Object
  extended by net.sf.freecol.common.model.FreeColObject
      extended by net.sf.freecol.common.model.FreeColGameObject
          extended by net.sf.freecol.common.model.Map
All Implemented Interfaces:
Location

public class Map
extends FreeColGameObject
implements Location

A rectangular isometric map. The map is represented as a two-dimensional array of tiles. Off-map destinations, such as Europe, can be reached via the HighSeas.

In theory, a Game might contain several Map instances connected by the HighSeas.


Nested Class Summary
private  class Map.AdjacentIterator
           
private  class Map.BorderAdjacentIterator
           
 class Map.CircleIterator
          An interator returning positions in a spiral starting at a given center tile.
static class Map.Direction
          The directions a Unit can move to.
static class Map.Layer
          The layers included in the map.
private  class Map.MapIterator
          Base class for internal iterators.
static class Map.Position
          Represents a position on the Map.
 class Map.WholeMapIterator
           
 
Field Summary
static int COST_INFINITY
          The infinity cost as used by #findPath(Unit, Tile, Tile).
private  float latitudePerRow
          Variable used to convert rows to latitude.
private  Map.Layer layer
          The highest map layer included.
private static java.util.logging.Logger logger
           
private  int maximumLatitude
          The latitude of the southern edge of the map.
private  int minimumLatitude
          The latitude of the northern edge of the map.
static int POLAR_HEIGHT
           
private  java.util.Map<java.lang.String,Region> regions
           
private  Tile[][] tiles
           
 
Fields inherited from class net.sf.freecol.common.model.FreeColGameObject
UNITS_TAG_NAME
 
Fields inherited from class net.sf.freecol.common.model.FreeColObject
ARRAY_SIZE, ID_ATTRIBUTE, ID_ATTRIBUTE_TAG, INFINITY, NO_ID, PARTIAL_ATTRIBUTE, UNDEFINED, VALUE_TAG
 
Constructor Summary
Map(Game game, java.lang.String id)
          Initiates a new Map with the given ID.
Map(Game game, Tile[][] tiles)
          Create a new Map from a collection of tiles.
Map(Game game, javax.xml.stream.XMLStreamReader in)
          Create a new Map from an Element in a DOM-parsed XML-tree.
 
Method Summary
 boolean add(Locatable locatable)
          Adds a Locatable to this Location.
private  void calculateLatitudePerRow()
          Calculates the LatitudePerRow value.
 boolean canAdd(Locatable locatable)
          Checks whether or not the specified locatable may be added to this Location.
 boolean contains(Locatable locatable)
          Checks if this Location contains the specified Locatable.
 PathNode findPath(Unit unit, Tile start, Tile end, Unit carrier, CostDecider costDecider)
          Finds a shortest path between the given tiles.
 PathNode findPathToEurope(Tile start)
          Finds the best path to Europe independently of any unit.
 PathNode findPathToEurope(Unit unit, Tile start, CostDecider costDecider)
          Finds the best path to Europe.
 java.util.Iterator<Map.Position> getAdjacentIterator(Map.Position centerPosition)
          Get an adjacent iterator.
 java.lang.Iterable<Tile> getAllTiles()
          Make the map usable as a parameter in the for-loop.
 java.util.Iterator<Map.Position> getBorderAdjacentIterator(Map.Position centerPosition)
          Get a border adjacent iterator.
 Map.CircleIterator getCircleIterator(Map.Position center, boolean isFilled, int radius)
          Get a circle iterator.
 java.util.List<Tile> getClaimableTiles(Player player, Tile centerTile, int radius)
          Gets the list of tiles that might be claimable by a settlement.
 Colony getColony()
          Returns null.
 Map.Direction getDirection(Tile t1, Tile t2)
          Returns the direction a unit needs to move in order to get from t1 to t2
 java.util.Iterator<Map.Position> getFloodFillIterator(Map.Position centerPosition)
          Get a flood fill iterator.
 GoodsContainer getGoodsContainer()
          Gets the GoodsContainer this Location use for storing it's goods.
 int getHeight()
          Returns the height of this Map.
 int getLatitude(int row)
          Get the latitude of the given map row.
 float getLatitudePerRow()
          Get the LatitudePerRow value.
 Map.Layer getLayer()
          Get the Layer value.
 StringTemplate getLocationName()
          Returns the name of this location.
 StringTemplate getLocationNameFor(Player player)
          Returns the name of this location for a particular player.
 int getMaximumLatitude()
          Get the MaximumLatitude value.
 int getMinimumLatitude()
          Get the MinimumLatitude value.
 Region getRegion(java.lang.String id)
          Returns the Region with the given ID.
 Region getRegionByName(java.lang.String id)
          Returns the Region with the given name.
 java.util.Collection<Region> getRegions()
          Returns a Collection containing all map regions.
 int getRow(int latitude)
          Get the map row with the given latitude.
 Settlement getSettlement()
          Returns null.
 Tile getTile()
          Returns null.
 Tile getTile(int x, int y)
          Returns the Tile at position (x, y).
 Tile getTile(Map.Position p)
          Returns the Tile at a requested position.
 int getUnitCount()
          Returns -1
 java.util.Iterator<Unit> getUnitIterator()
          Returns an Iterator for an empty list.
 java.util.List<Unit> getUnitList()
          Returns an empty list.
 Map.WholeMapIterator getWholeMapIterator()
          Gets an Iterator of every Tile on the map.
 int getWidth()
          Returns the width of this Map.
static java.lang.String getXMLElementTagName()
          Returns the tag name of the root element representing this object.
 boolean isLandWithinDistance(int x, int y, int distance)
          Searches for land within the given radius.
 boolean isPolar(Tile tile)
          Is a tile in the map in a polar region?
 boolean isValid(int x, int y)
          Checks whether a position is valid (within the map limits).
static boolean isValid(int x, int y, int width, int height)
          Checks if the given position is valid.
 boolean isValid(Map.Position position)
          Checks whether a position is valid (within the map limits).
static boolean isValid(Map.Position position, int width, int height)
          Checks whether a position is valid.
protected  void readFromXMLImpl(javax.xml.stream.XMLStreamReader in)
          Initialize this object from an XML-representation of this object.
 boolean remove(Locatable locatable)
          Removes a Locatable from this Location.
 PathNode search(Unit unit, Tile startTile, GoalDecider gd, CostDecider costDecider, int maxTurns, Unit carrier)
          Finds a path to a goal determined by the given GoalDecider.
 void setLayer(Map.Layer newLayer)
          Set the Layer value.
 void setMaximumLatitude(int newMaximumLatitude)
          Set the MaximumLatitude value.
 void setMinimumLatitude(int newMinimumLatitude)
          Set the MinimumLatitude value.
 void setRegion(Region region)
          Describe setRegion method here.
 void setTile(Tile tile, int x, int y)
          Sets the given tile the the given coordinates.
protected  void toXMLImpl(javax.xml.stream.XMLStreamWriter out, Player player, boolean showAll, boolean toSavedGame)
          This method writes an XML-representation of this object to the given stream.
protected  void writeAttributes(javax.xml.stream.XMLStreamWriter out, Player player, boolean showAll, boolean toSavedGame)
           
protected  void writeChildren(javax.xml.stream.XMLStreamWriter out, Player player, boolean showAll, boolean toSavedGame)
           
 
Methods inherited from class net.sf.freecol.common.model.FreeColGameObject
dispose, disposeList, equals, equals, fundamentalDispose, getFreeColGameObject, getFreeColGameObject, getGame, getIntegerID, getSpecification, hashCode, isDisposed, isUninitialized, newLocation, readFromXML, readFromXMLPartialByClass, setDefaultId, setGame, setId, toString, toXML, toXMLImpl, toXMLPartialByClass, updateFreeColGameObject
 
Methods inherited from class net.sf.freecol.common.model.FreeColObject
addPropertyChangeListener, addPropertyChangeListener, dumpObject, fireIndexedPropertyChange, fireIndexedPropertyChange, fireIndexedPropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getAttribute, getAttribute, getAttribute, getAttribute, getAttribute, getId, getPropertyChangeListeners, getPropertyChangeListeners, hasAbility, hasAttribute, hasListeners, readAttributes, readAttributes, readChild, readChild, readChildren, readChildren, readFromArrayElement, readFromArrayElement, readFromListElement, readFromXMLElement, readFromXMLImpl, readFromXMLPartialImpl, removePropertyChangeListener, removePropertyChangeListener, save, save, setSpecification, toXML, toXML, toXMLElement, toXMLElement, toXMLElement, toXMLElement, toXMLElementPartial, toXMLPartialImpl, writeAttribute, writeAttributes, writeChildren
 
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
 

Field Detail

logger

private static final java.util.logging.Logger logger

POLAR_HEIGHT

public static final int POLAR_HEIGHT
See Also:
Constant Field Values

COST_INFINITY

public static final int COST_INFINITY
The infinity cost as used by #findPath(Unit, Tile, Tile).

See Also:
Constant Field Values

tiles

private Tile[][] tiles

layer

private Map.Layer layer
The highest map layer included.


minimumLatitude

private int minimumLatitude
The latitude of the northern edge of the map. A negative value indicates northern latitude, a positive value southern latitude. Thus, -30 equals 30°N, and 40 equals 40°S.


maximumLatitude

private int maximumLatitude
The latitude of the southern edge of the map. A negative value indicates northern latitude, a positive value southern latitude. Thus, -30 equals 30°N, and 40 equals 40°S.


latitudePerRow

private float latitudePerRow
Variable used to convert rows to latitude.


regions

private final java.util.Map<java.lang.String,Region> regions
Constructor Detail

Map

public Map(Game game,
           Tile[][] tiles)
Create a new Map from a collection of tiles.

Parameters:
game - The Game this map belongs to.
tiles - The 2D array of tiles.

Map

public Map(Game game,
           javax.xml.stream.XMLStreamReader in)
    throws javax.xml.stream.XMLStreamException
Create a new Map from an Element in a DOM-parsed XML-tree.

Parameters:
game - The Game this map belongs to.
in - The input stream containing the XML.
Throws:
javax.xml.stream.XMLStreamException - if a problem was encountered during parsing.

Map

public Map(Game game,
           java.lang.String id)
Initiates a new Map with the given ID. The object should later be initialized by calling either FreeColGameObject.readFromXML(XMLStreamReader) or FreeColObject.readFromXMLElement(Element).

Parameters:
game - The Game in which this object belong.
id - The unique identifier for this object.
Method Detail

getRegions

public java.util.Collection<Region> getRegions()
Returns a Collection containing all map regions.

Returns:
a Collection containing all map regions

getLayer

public final Map.Layer getLayer()
Get the Layer value.

Returns:
a Layer value

setLayer

public final void setLayer(Map.Layer newLayer)
Set the Layer value.

Parameters:
newLayer - The new Layer value.

getMinimumLatitude

public final int getMinimumLatitude()
Get the MinimumLatitude value.

Returns:
an int value

setMinimumLatitude

public final void setMinimumLatitude(int newMinimumLatitude)
Set the MinimumLatitude value.

Parameters:
newMinimumLatitude - The new MinimumLatitude value.

getMaximumLatitude

public final int getMaximumLatitude()
Get the MaximumLatitude value.

Returns:
an int value

setMaximumLatitude

public final void setMaximumLatitude(int newMaximumLatitude)
Set the MaximumLatitude value.

Parameters:
newMaximumLatitude - The new MaximumLatitude value.

getLatitudePerRow

public final float getLatitudePerRow()
Get the LatitudePerRow value.

Returns:
a float value

calculateLatitudePerRow

private final void calculateLatitudePerRow()
Calculates the LatitudePerRow value.


getLatitude

public int getLatitude(int row)
Get the latitude of the given map row.

Parameters:
row - an int value
Returns:
an int value

getRow

public int getRow(int latitude)
Get the map row with the given latitude.

Parameters:
latitude - an int value
Returns:
an int value

getRegion

public Region getRegion(java.lang.String id)
Returns the Region with the given ID.

Parameters:
id - a String value
Returns:
a Region value

getRegionByName

public Region getRegionByName(java.lang.String id)
Returns the Region with the given name.

Parameters:
id - a String value
Returns:
a Region value

setRegion

public void setRegion(Region region)
Describe setRegion method here.

Parameters:
region - a Region value

isPolar

public boolean isPolar(Tile tile)
Is a tile in the map in a polar region?

Parameters:
tile - The Tile to examine.
Returns:
True if the tile is in a polar region.

getClaimableTiles

public java.util.List<Tile> getClaimableTiles(Player player,
                                              Tile centerTile,
                                              int radius)
Gets the list of tiles that might be claimable by a settlement. We can not do a simple iteration of the rings because this allows settlements to claim tiles across unclaimable gaps (e.g. Aztecs owning tiles on nearby islands). So we have to only allow tiles that are adjacent to a known connected tile.

Parameters:
player - The Player that intends to found a settlement.
centerTile - The intended settlement center Tile.
radius - The radius of the settlement.
Returns:
A list of potentially claimable tiles.

findPath

public PathNode findPath(Unit unit,
                         Tile start,
                         Tile end,
                         Unit carrier,
                         CostDecider costDecider)
Finds a shortest path between the given tiles. The tile at the end will not be checked for validity. Using A* with the Manhatten distance as the heuristics. The data structure for the open list is a combined structure: using a HashMap for membership tests and a PriorityQueue for getting the node with the minimal f (cost+heuristics). This gives O(1) on membership test and O(log N) for remove-best and insertions. The data structure for the closed list is simply a HashMap.

Parameters:
unit - The Unit to find the path for.
start - The Tile in which the path starts from.
end - The Tile at the end of the path.
carrier - An optional carrier Unit that currently holds the unit, or null if it is not presently on a carrier.
costDecider - An optional CostDecider for determining the movement costs (uses default cost deciders for the unit/s if not provided).
Returns:
A PathNode for the first tile in the path, or null if none found.
Throws:
java.lang.IllegalArgumentException - If start, end, or unitnull, or start equals end.

findPathToEurope

public PathNode findPathToEurope(Unit unit,
                                 Tile start,
                                 CostDecider costDecider)
Finds the best path to Europe.

Parameters:
unit - The Unit that should be used to determine whether or not a path is legal.
start - The starting Tile.
costDecider - An optional CostDecider responsible for determining the path cost.
Returns:
The path to Europe, or null if not found.
See Also:
Europe

findPathToEurope

public PathNode findPathToEurope(Tile start)
Finds the best path to Europe independently of any unit. This method is meant to be executed by the server/AI code, with complete knowledge of the map

Parameters:
start - The starting Tile.
Returns:
The path to the target or null if no target can be found.
See Also:
Europe

search

public PathNode search(Unit unit,
                       Tile startTile,
                       GoalDecider gd,
                       CostDecider costDecider,
                       int maxTurns,
                       Unit carrier)
Finds a path to a goal determined by the given GoalDecider. A GoalDecider is typically defined inline to serve a specific need. Using Dijkstra's algorithm with a closedList for marking the visited nodes and using a PriorityQueue for getting the next edge with the least cost. This implementation could be improved by having the visited attribute stored on each Tile in order to avoid both of the HashMaps currently being used to serve this purpose.

Parameters:
unit - The Unit to find a path for.
startTile - The Tile to start the search from.
gd - The object responsible for determining whether a given PathNode is a goal or not.
costDecider - An optional CostDecider responsible for determining the path cost.
maxTurns - The maximum number of turns the given Unit is allowed to move. This is the maximum search range for a goal.
carrier - The carrier the unit is currently onboard or null if the unit is either not onboard a carrier or should not use the carrier while finding the path.
Returns:
The path to a goal determined by the given GoalDecider.

isLandWithinDistance

public boolean isLandWithinDistance(int x,
                                    int y,
                                    int distance)
Searches for land within the given radius.

Parameters:
x - X-component of the position to search from.
y - Y-component of the position to search from.
distance - The radius that should be searched for land, given in number of tiles.
Returns:
true if there is land within the given radius and false otherwise.

getTile

public Tile getTile(Map.Position p)
Returns the Tile at a requested position.

Parameters:
p - The position.
Returns:
The Tile at the given position.

getTile

public Tile getTile(int x,
                    int y)
Returns the Tile at position (x, y). 'x' specifies a column and 'y' specifies a row. (0, 0) is the Tile at the top-left corner of the Map.

Parameters:
x - The x-coordinate of the Tile.
y - The y-coordinate of the Tile.
Returns:
The Tile at position (x, y) or null if the position is invalid.

setTile

public void setTile(Tile tile,
                    int x,
                    int y)
Sets the given tile the the given coordinates.

Parameters:
x - The x-coordinate of the Tile.
y - The y-coordinate of the Tile.
tile - The Tile.

getWidth

public int getWidth()
Returns the width of this Map.

Returns:
The width of this Map.

getHeight

public int getHeight()
Returns the height of this Map.

Returns:
The height of this Map.

getDirection

public Map.Direction getDirection(Tile t1,
                                  Tile t2)
Returns the direction a unit needs to move in order to get from t1 to t2

Parameters:
t1 - The tile to move from.
t2 - The target tile if moving from t1 in the direction returned by this method.
Returns:
The direction you need to move from t1 in order to reach t2, or null if the two specified tiles are not neighbours.

getWholeMapIterator

public Map.WholeMapIterator getWholeMapIterator()
Gets an Iterator of every Tile on the map.

Returns:
the Iterator.

getAdjacentIterator

public java.util.Iterator<Map.Position> getAdjacentIterator(Map.Position centerPosition)
Get an adjacent iterator.

Parameters:
centerPosition - The center position to iterate around
Returns:
Iterator

getBorderAdjacentIterator

public java.util.Iterator<Map.Position> getBorderAdjacentIterator(Map.Position centerPosition)
Get a border adjacent iterator.

Parameters:
centerPosition - The center position to iterate around
Returns:
Iterator

getFloodFillIterator

public java.util.Iterator<Map.Position> getFloodFillIterator(Map.Position centerPosition)
Get a flood fill iterator.

Parameters:
centerPosition - The center position to iterate around
Returns:
Iterator

getCircleIterator

public Map.CircleIterator getCircleIterator(Map.Position center,
                                            boolean isFilled,
                                            int radius)
Get a circle iterator.

Parameters:
center - The center position to iterate around
isFilled - True to get all of the positions in the circle
radius - Radius of circle
Returns:
Iterator

isValid

public boolean isValid(Map.Position position)
Checks whether a position is valid (within the map limits).

Parameters:
position - The position
Returns:
True if it is valid

isValid

public boolean isValid(int x,
                       int y)
Checks whether a position is valid (within the map limits).

Parameters:
x - X coordinate
y - Y coordinate
Returns:
True if it is valid

isValid

public static boolean isValid(Map.Position position,
                              int width,
                              int height)
Checks whether a position is valid.

Parameters:
position - The position
width - The width of the map.
height - The height of the map.
Returns:
true if the given position is within the bounds of the map and false otherwise

isValid

public static boolean isValid(int x,
                              int y,
                              int width,
                              int height)
Checks if the given position is valid.

Parameters:
x - The x-coordinate of the position.
y - The y-coordinate of the position.
width - The width of the map.
height - The height of the map.
Returns:
true if the given position is within the bounds of the map and false otherwise

getAllTiles

public java.lang.Iterable<Tile> getAllTiles()
Make the map usable as a parameter in the for-loop. Returns all Tiles based on the order of the WholeMapIterator.

Returns:
An Iterable that can be used to get an iterator for all tiles of the map.

getTile

public Tile getTile()
Returns null.

Specified by:
getTile in interface Location
Returns:
null

getLocationName

public StringTemplate getLocationName()
Returns the name of this location.

Specified by:
getLocationName in interface Location
Returns:
The name of this location.

getLocationNameFor

public StringTemplate getLocationNameFor(Player player)
Returns the name of this location for a particular player.

Specified by:
getLocationNameFor in interface Location
Parameters:
player - The Player to return the name for.
Returns:
The name of this location.

add

public boolean add(Locatable locatable)
Adds a Locatable to this Location. It the given Locatable is a Unit, its location is set to its entry location, otherwise nothing happens.

Specified by:
add in interface Location
Parameters:
locatable - The Locatable to add to this Location.

remove

public boolean remove(Locatable locatable)
Removes a Locatable from this Location.

Specified by:
remove in interface Location
Parameters:
locatable - The Locatable to remove from this Location.

contains

public boolean contains(Locatable locatable)
Checks if this Location contains the specified Locatable.

Specified by:
contains in interface Location
Parameters:
locatable - The Locatable to test the presence of.
Returns:
  • true if the specified Locatable is on this Location and
  • false otherwise.

canAdd

public boolean canAdd(Locatable locatable)
Checks whether or not the specified locatable may be added to this Location.

Specified by:
canAdd in interface Location
Parameters:
locatable - The Locatable to add.
Returns:
The result.

getUnitCount

public int getUnitCount()
Returns -1

Specified by:
getUnitCount in interface Location
Returns:
-1

getUnitList

public java.util.List<Unit> getUnitList()
Returns an empty list.

Specified by:
getUnitList in interface Location
Returns:
an empty list

getUnitIterator

public java.util.Iterator<Unit> getUnitIterator()
Returns an Iterator for an empty list.

Specified by:
getUnitIterator in interface Location
Returns:
The Iterator.

getGoodsContainer

public GoodsContainer getGoodsContainer()
Gets the GoodsContainer this Location use for storing it's goods.

Specified by:
getGoodsContainer in interface Location
Returns:
The GoodsContainer or null if the Location cannot store any goods.

getSettlement

public Settlement getSettlement()
Returns null.

Specified by:
getSettlement in interface Location
Returns:
null

getColony

public Colony getColony()
Returns null.

Specified by:
getColony in interface Location
Returns:
null

toXMLImpl

protected void toXMLImpl(javax.xml.stream.XMLStreamWriter out,
                         Player player,
                         boolean showAll,
                         boolean toSavedGame)
                  throws javax.xml.stream.XMLStreamException
This method writes an XML-representation of this object to the given stream.

Only attributes visible to the given Player will be added to that representation if showAll is set to false.

Specified by:
toXMLImpl in class FreeColGameObject
Parameters:
out - The target stream.
player - The Player this XML-representation should be made for, or null if showAll == true.
showAll - Only attributes visible to player will be added to the representation if showAll is set to false.
toSavedGame - If true then information that is only needed when saving a game is added.
Throws:
javax.xml.stream.XMLStreamException - if there are any problems writing to the stream.

writeAttributes

protected void writeAttributes(javax.xml.stream.XMLStreamWriter out,
                               Player player,
                               boolean showAll,
                               boolean toSavedGame)
                        throws javax.xml.stream.XMLStreamException
Throws:
javax.xml.stream.XMLStreamException

writeChildren

protected void writeChildren(javax.xml.stream.XMLStreamWriter out,
                             Player player,
                             boolean showAll,
                             boolean toSavedGame)
                      throws javax.xml.stream.XMLStreamException
Throws:
javax.xml.stream.XMLStreamException

readFromXMLImpl

protected void readFromXMLImpl(javax.xml.stream.XMLStreamReader in)
                        throws javax.xml.stream.XMLStreamException
Initialize this object from an XML-representation of this object.

Overrides:
readFromXMLImpl in class FreeColObject
Parameters:
in - The input stream with the XML.
Throws:
javax.xml.stream.XMLStreamException - if a problem was encountered during parsing.

getXMLElementTagName

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

Returns:
"map".