Package net.sf.freecol.common.model
Class Map
- java.lang.Object
-
- net.sf.freecol.common.model.FreeColObject
-
- net.sf.freecol.common.model.FreeColGameObject
-
- net.sf.freecol.common.model.Map
-
- All Implemented Interfaces:
java.lang.Comparable<FreeColObject>
,Location
,ObjectWithId
public class Map extends FreeColGameObject implements Location
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description private class
Map.CircleIterator
An iterator returning positions in a spiral starting at a given center tile.static class
Map.Layer
The layers included in the map.private static class
Map.MoveCandidate
Internal class for evaluating a candidate move.private static class
Map.MoveStep
Possible actions by the unit travelling along a path in consideration of the next tile.static class
Map.Position
A position on the Map.private static interface
Map.SearchHeuristic
Simple interface to supply a heuristic to the A* routine.
-
Field Summary
Fields Modifier and Type Field Description private int
height
The width and height of the map.private static java.lang.String
HEIGHT_TAG
private float
latitudePerRow
Variable used to convert rows to latitude.private Map.Layer
layer
The highest map layer included.private static java.lang.String
LAYER_TAG
private static java.util.logging.Logger
logger
private static java.lang.String
MAXIMUM_LATITUDE_TAG
private int
maximumLatitude
The latitude of the southern edge of the map.private static java.lang.String
MINIMUM_LATITUDE_TAG
private int
minimumLatitude
The latitude of the northern edge of the map.static int
POLAR_HEIGHT
The number of tiles from the upper edge that are considered polar by default.private java.util.List<Region>
regions
The regions on the map.static java.lang.String
TAG
private Tile[][]
tileArray
The tiles that this map contains, as a 2D array.private java.util.List<Tile>
tileList
The tiles that this map contains, as a list.private boolean
traceSearch
The search tracing status.private Map.SearchHeuristic
trivialSearchHeuristic
A trivial search heuristic that always returns zero.private int
width
The width and height of the map.private static java.lang.String
WIDTH_TAG
-
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.Location
LOCATION_RANK_EUROPE, LOCATION_RANK_HIGHSEAS, LOCATION_RANK_NOWHERE
-
-
Constructor Summary
Constructors Constructor Description Map(Game game, int width, int height)
Create a newMap
from a collection of tiles.Map(Game game, java.lang.String id)
Creates a newMap
with the given object identifier.Map(Game game, FreeColXMLReader xr)
Create a newMap
from an input stream.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description boolean
add(Locatable locatable)
Adds aLocatable
to this Location.void
addRegion(Region region)
Adds a region to this map.private void
calculateLatitudePerRow()
Recalculate the latitude/row from the current maximum and minimum.boolean
canAdd(Locatable locatable)
Checks whether or not the specified locatable may be added to thisLocation
.Constants.IntegrityType
checkIntegrity(boolean fix, LogBuilder lb)
Checks the integrity of this game object.void
clearRegions()
Clear the regions list.void
collectStartingTiles(java.util.List<Tile> eastTiles, java.util.List<Tile> westTiles)
Collect lists of valid starting tiles on this map.boolean
contains(Locatable locatable)
Checks if thisLocation
contains the specifiedLocatable
.<T extends FreeColObject>
booleancopyIn(T other)
Copy another FreeColObject into this one if it is compatible.private PathNode
findMapPath(Unit unit, Tile start, Tile end, Unit carrier, CostDecider costDecider, LogBuilder lb)
Find the quickest path for a unit (with optional carrier) from a start tile to an end tile.PathNode
findPath(Unit unit, Location start, Location end, Unit carrier, CostDecider costDecider, LogBuilder lb)
Find the quickest path for a unit (with optional carrier) from a start location to an end location.private Location
findRealEnd(Unit unit, Location end)
Destination argument test for path searches.private void
finishPath(PathNode path, Unit unit, LogBuilder lb)
Finish processing a path.void
fixupRegions()
Fix the region parent/child relationships.private void
floodFill(int contig, int ymax, int xmax, boolean[][] waterMap)
Performs fill flood action and calculationsstatic boolean[][]
floodFillBool(boolean[][] boolmap, int x, int y)
Flood fills from a givenPosition
p, based on connectivity information encoded in boolmapstatic boolean[][]
floodFillBool(boolean[][] boolmap, int x, int y, int limit)
Flood fills from a givenPosition
p, based on connectivity information encoded in boolmapvoid
forEachTile(java.util.function.Consumer<Tile> consumer)
Perform an action on each tile.void
forEachTile(java.util.function.Predicate<Tile> predicate, java.util.function.Consumer<Tile> consumer)
Perform an action on each tile that matches a predicate.void
forSubMap(int x, int y, int w, int h, java.util.function.Consumer<Tile> consumer)
Iterates through a rectangular subpart of the Map.Tile
getAdjacentTile(int x, int y, Direction direction)
Gets the adjacent tile in a given direction from the given coordinates.Tile
getAdjacentTile(Tile tile, Direction direction)
Gets the adjacent tile in a given direction from a given tile.private PathNode
getBestEntryPath(Unit unit, Tile tile, Unit carrier, CostDecider costDecider)
Gets the best (closest) path location for this unit to reach a given tile from off the map.Tile
getBestEntryTile(Unit unit, Tile tile, Unit carrier, CostDecider costDecider)
Gets the best (closest) entry location for this unit to reach a given tile from off the map.java.util.Iterator<Tile>
getCircleIterator(Tile center, boolean isFilled, int radius)
Gets a circle iterator.java.lang.Iterable<Tile>
getCircleTiles(Tile center, boolean isFilled, int radius)
Gets an iterable for all the tiles in a circle using an underlying CircleIterator.Tile
getClosestTile(Tile tile, java.util.Collection<Tile> tiles)
Get the closest tile to a given one from a list of other tiles.Colony
getColony()
Get the colony at this location.Direction
getDirection(Tile t1, Tile t2)
Gets the direction a unit needs to move in order to get fromt1
tot2
int
getDistance(Tile t1, Tile t2)
Gets the distance between two tiles.java.util.Map<java.lang.String,Region>
getFixedRegions()
Get the fixed regions indexed by key.GoodsContainer
getGoodsContainer()
Gets theGoodsContainer
thisLocation
use for storing it's goods.int
getHeight()
Gets the height of this map.IndianSettlement
getIndianSettlement()
Gets the native settlement at this location.Tile
getLandWithinDistance(int x, int y, int distance)
Searches for land within the given radius.int
getLatitude(int row)
Gets the latitude of the given map row.float
getLatitudePerRow()
Get the latitude/row.Map.Layer
getLayer()
Get the layer.java.lang.String
getLocationImageKey()
Get an image key for this location.StringTemplate
getLocationLabel()
Get a label for this location.StringTemplate
getLocationLabelFor(Player player)
Get a label for this location for a particular player.private Map.SearchHeuristic
getManhattenHeuristic(Tile endTile)
Gets a search heuristic using the Manhatten distance to an end tile.int
getMaximumLatitude()
Get the maximum latitude.int
getMinimumLatitude()
Get the minimum latitude.Tile
getRandomLandTile(java.util.Random random)
Select a random land tile on the map.int
getRank()
Get a integer for this location, for the benefit of location comparators.Region
getRegionByKey(java.lang.String key)
Gets aRegion
by name key.Region
getRegionByName(java.lang.String name)
Gets aRegion
by name.java.util.Collection<Region>
getRegions()
Gets the regions in this map.static Direction
getRoughDirection(Tile src, Tile dst)
Get the approximate direction from one tile to another.int
getRow(int latitude)
Gets the map row with the given latitude.boolean
getSearchTrace()
Gets the search tracing status.Settlement
getSettlement()
Gets theSettlement
thisLocation
is located in.java.util.List<Tile>
getShuffledTiles(java.util.Random random)
Get a shuffled list of all the tiles.Tile
getTile()
Gets the location tile.Tile
getTile(int x, int y)
Gets the Tile at position (x, y).Tile
getTile(Map.Position p)
Gets the Tile at a requested position.java.util.List<Tile>
getTileList(java.util.function.Predicate<Tile> predicate)
Get a list of all the tiles that match a predicate.java.util.Set<Tile>
getTileSet(java.util.function.Predicate<Tile> predicate)
Get a list of all the tiles that match a predicate.int
getUnitCount()
Gets the number of units at this Location.java.util.List<Unit>
getUnitList()
Gets a list of all the units present at this location.java.util.stream.Stream<Unit>
getUnits()
Gets a stream of all the units present at this location.int
getWidth()
Gets the width of this map.java.lang.String
getXMLTagName()
Get the serialization tag for this object.Tile
importTile(Tile other, int x, int y, Map.Layer layer)
Import a tile, possibly from another game.static boolean
inBox(int x, int y, int width, int height)
Checks if an (x,y) coordinate tuple is within a map of specified width and height.private void
initializeTraceSearch()
Enable full path logging by default if in PATHS debug mode.boolean
isPolar(Tile tile)
Is a tile in the map in a polar region?static boolean
isSameContiguity(Location l1, Location l2)
Are two locations at least in the same contiguous land/sea-mass? This routine is here because Location is an interface.static boolean
isSameLocation(Location l1, Location l2)
Are two locations non-null and either the same or at the same tile.boolean
isValid(int x, int y)
Checks whether a position is valid (within the map limits).boolean
isValid(Map.Position position)
Checks whether a position is valid (within the map limits).boolean
populateTiles(java.util.function.BiFunction<java.lang.Integer,java.lang.Integer,Tile> func)
Populate the map.protected void
readAttributes(FreeColXMLReader xr)
Reads the attributes of this object from an XML stream.protected void
readChild(FreeColXMLReader xr)
Reads a single child object.protected void
readChildren(FreeColXMLReader xr)
Reads the children of this object from an XML stream.boolean
remove(Locatable locatable)
Removes aLocatable
from this Location.void
resetContiguity()
Sets the contiguity identifier for all tiles.void
resetHighSeas(int distToLandFromHighSeas, int maxDistanceToEdge)
Places the "high seas"-tiles on the border of this map.void
resetHighSeasCount()
Sets the high seas count for all tiles connected to the high seas.void
resetLayers()
Reset layer to reflect what is actually there.Map
scale(int width, int height)
Scale the map into the specified size.PathNode
search(Unit unit, Location start, GoalDecider goalDecider, CostDecider costDecider, int maxTurns, Unit carrier, LogBuilder lb)
Searches for a goal.Tile
searchCircle(Tile start, GoalDecider goalDecider, int radius)
Searches for a tile within a radius of a starting tile.private PathNode
searchMap(Unit unit, Tile start, GoalDecider goalDecider, CostDecider costDecider, int maxTurns, Unit carrier, Map.SearchHeuristic searchHeuristic, LogBuilder lb)
Searches for a path to a goal determined by the givenGoalDecider
.void
setLayer(Map.Layer newLayer)
Set the layer.void
setMaximumLatitude(int newMaximumLatitude)
Set the maxmimum latitude.void
setMinimumLatitude(int newMinimumLatitude)
Set the minimum latitude.boolean
setSearchTrace(boolean trace)
Sets the search tracing status.private boolean
setTile(Tile tile, int x, int y)
Set the tile at the given coordinates.private java.lang.String
setTiles(int width, int height)
Initialize the tile shape.java.util.List<Tile>
subMap(int x, int y, int w, int h)
Collect the tiles in a rectangular portion of the map.java.lang.String
toShortString()
Get a short description of this location.Location
up()
Promote this location to a more meaningful one if possible.private boolean
updateTile(Tile tile)
Update a tile in this map from the given tile.private java.lang.String
updateTiles(int width, int height)
Update the tile shape, however it is an error to change the map size after the initial setting.private boolean
usedCarrier(PathNode path)
Was a carrier used previously on a path? Beware! This is special case code for partially constructed paths that do not yet have valid .next links, so we can not use the generic PathNode routines.protected void
writeAttributes(FreeColXMLWriter xw)
Write the attributes of this object to a stream.protected void
writeChildren(FreeColXMLWriter xw)
Write the children of this object to a stream.-
Methods inherited from class net.sf.freecol.common.model.FreeColGameObject
dispose, disposeResources, equals, fundamentalDispose, getClassIndex, getDisposables, getGame, getLinkTarget, getSpecification, hashCode, intern, 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, getAbilities, 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, readFromXMLPartial, removeAbilities, removeAbility, removeFeatures, removeModifier, removeModifiers, removePropertyChangeListener, removePropertyChangeListener, save, save, save, save, serialize, serialize, serialize, serialize, setId, toString, 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
-
POLAR_HEIGHT
public static final int POLAR_HEIGHT
The number of tiles from the upper edge that are considered polar by default.- See Also:
- Constant Field Values
-
width
private int width
The width and height of the map.
-
height
private int height
The width and height of the map.
-
tileArray
private Tile[][] tileArray
The tiles that this map contains, as a 2D array. This starts out unassigned, but is initialized in setTiles(). Then the individual tiles are filled in with setTile(), however once a Tile is present further calls to setTile will copyIn to it.
-
tileList
private java.util.List<Tile> tileList
The tiles that this map contains, as a list. This is populated in setTile().
-
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 degrees N, and 40 equals 40 degrees 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 degrees N, and 40 equals 40 degrees S.
-
latitudePerRow
private float latitudePerRow
Variable used to convert rows to latitude.
-
regions
private final java.util.List<Region> regions
The regions on the map.
-
traceSearch
private boolean traceSearch
The search tracing status.
-
trivialSearchHeuristic
private Map.SearchHeuristic trivialSearchHeuristic
A trivial search heuristic that always returns zero.
-
HEIGHT_TAG
private static final java.lang.String HEIGHT_TAG
- See Also:
- Constant Field Values
-
LAYER_TAG
private static final java.lang.String LAYER_TAG
- See Also:
- Constant Field Values
-
MAXIMUM_LATITUDE_TAG
private static final java.lang.String MAXIMUM_LATITUDE_TAG
- See Also:
- Constant Field Values
-
MINIMUM_LATITUDE_TAG
private static final java.lang.String MINIMUM_LATITUDE_TAG
- See Also:
- Constant Field Values
-
WIDTH_TAG
private static final java.lang.String WIDTH_TAG
- See Also:
- Constant Field Values
-
-
Constructor Detail
-
Map
public Map(Game game, int width, int height)
Create a newMap
from a collection of tiles.- Parameters:
game
- The enclosingGame
.width
- The map width.height
- The map height.
-
Map
public Map(Game game, FreeColXMLReader xr) throws javax.xml.stream.XMLStreamException
Create a newMap
from an input stream.- Parameters:
game
- The enclosingGame
.xr
- 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)
Creates a newMap
with the given object identifier. The object should be initialized later.- Parameters:
game
- The enclosingGame
.id
- The object identifier.
-
-
Method Detail
-
initializeTraceSearch
private void initializeTraceSearch()
Enable full path logging by default if in PATHS debug mode.
-
getWidth
public int getWidth()
Gets the width of this map.- Returns:
- The width of this map.
-
getHeight
public int getHeight()
Gets the height of this map.- Returns:
- The height of this map.
-
inBox
public static boolean inBox(int x, int y, int width, int height)
Checks if an (x,y) coordinate tuple is within a map of specified width and height.- 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.
-
isValid
public boolean isValid(int x, int y)
Checks whether a position is valid (within the map limits).- Parameters:
x
- The X coordinate to check.y
- The Y coordinate to check.- Returns:
- True if the coordinates are valid.
-
isValid
public boolean isValid(Map.Position position)
Checks whether a position is valid (within the map limits).- Parameters:
position
- ThePosition
to check.- Returns:
- True if the position is valid.
-
setTiles
private java.lang.String setTiles(int width, int height)
Initialize the tile shape. This must be called *once* per map.- Parameters:
width
- The new map width.height
- The new map height.- Returns:
- An error message if setting the tile array was invalid, null if valid.
-
updateTiles
private java.lang.String updateTiles(int width, int height)
Update the tile shape, however it is an error to change the map size after the initial setting.- Parameters:
width
- The new map width.height
- The new map height.- Returns:
- An error message if setting the tile array was invalid, null if valid.
-
getTile
public Tile getTile(int x, int y)
Gets 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 theTile
.y
- The y-coordinate of theTile
.- Returns:
- The
Tile
at (x, y), or null if the position is invalid.
-
getTile
public Tile getTile(Map.Position p)
Gets the Tile at a requested position.- Parameters:
p
- ThePosition
to query.- Returns:
- The
Tile
at the given position.
-
setTile
private boolean setTile(Tile tile, int x, int y)
Set the tile at the given coordinates. This can be done *once* per tile. Currently that is enforced by calling setTile() only from populateTiles() where the map is being built or indirectly through updateTile() where the absence of the tile is checked.- Parameters:
x
- The x-coordinate of theTile
.y
- The y-coordinate of theTile
.tile
- TheTile
to set.- Returns:
- True if the
Tile
was updated.
-
updateTile
private boolean updateTile(Tile tile)
Update a tile in this map from the given tile.- Parameters:
tile
- TheTile
to update from.- Returns:
- True if the tile was updated.
-
getLayer
public final Map.Layer getLayer()
Get the layer.- Returns:
- The maximum implemented layer on this map.
-
setLayer
public final void setLayer(Map.Layer newLayer)
Set the layer.- Parameters:
newLayer
- The new maximum implemented layer for this map.
-
getMinimumLatitude
public final int getMinimumLatitude()
Get the minimum latitude.- Returns:
- The minimum latitude of this map.
-
setMinimumLatitude
public final void setMinimumLatitude(int newMinimumLatitude)
Set the minimum latitude.- Parameters:
newMinimumLatitude
- The new minimum latitude for this map.
-
getMaximumLatitude
public final int getMaximumLatitude()
Get the maximum latitude.- Returns:
- The maximum latitude of this map.
-
setMaximumLatitude
public final void setMaximumLatitude(int newMaximumLatitude)
Set the maxmimum latitude.- Parameters:
newMaximumLatitude
- The new maximum latitude for this map.
-
getLatitudePerRow
public final float getLatitudePerRow()
Get the latitude/row.- Returns:
- The latitude change between rows.
-
calculateLatitudePerRow
private final void calculateLatitudePerRow()
Recalculate the latitude/row from the current maximum and minimum.
-
getLatitude
public int getLatitude(int row)
Gets the latitude of the given map row.- Parameters:
row
- The row to check.- Returns:
- The row latitude.
-
getRow
public int getRow(int latitude)
Gets the map row with the given latitude.- Parameters:
latitude
- The latitude to find.- Returns:
- The row closest to the supplied latitude.
-
getRegions
public java.util.Collection<Region> getRegions()
Gets the regions in this map.- Returns:
- All the regions in this map.
-
addRegion
public void addRegion(Region region)
Adds a region to this map.- Parameters:
region
- TheRegion
to add.
-
clearRegions
public void clearRegions()
Clear the regions list.
-
getFixedRegions
public java.util.Map<java.lang.String,Region> getFixedRegions()
Get the fixed regions indexed by key.- Returns:
- A map of the fixed regions.
-
getRegionByKey
public Region getRegionByKey(java.lang.String key)
Gets aRegion
by name key.- Parameters:
key
- The name key to lookup the region with.- Returns:
- The
Region
with the given name key, or null if none found.
-
getRegionByName
public Region getRegionByName(java.lang.String name)
Gets aRegion
by name.- Parameters:
name
- The region name.- Returns:
- The
Region
with the given name, or null if not found.
-
isSameLocation
public static final boolean isSameLocation(Location l1, Location l2)
Are two locations non-null and either the same or at the same tile. This routine is here because Location is an interface.- Parameters:
l1
- The firstLocation
.l2
- The secondLocation
.- Returns:
- True if the locations are the same or at the same tile.
-
isSameContiguity
public static final boolean isSameContiguity(Location l1, Location l2)
Are two locations at least in the same contiguous land/sea-mass? This routine is here because Location is an interface.- Parameters:
l1
- The firstLocation
.l2
- The secondLocation
.- Returns:
- True if the locations are the same or in the same land/sea-mass.
-
isPolar
public boolean isPolar(Tile tile)
Is a tile in the map in a polar region?- Parameters:
tile
- TheTile
to examine.- Returns:
- True if the tile is in a polar region.
-
getDirection
public Direction getDirection(Tile t1, Tile t2)
Gets the direction a unit needs to move in order to get fromt1
tot2
- Parameters:
t1
- The tile to move from.t2
- The target tile if moving fromt1
in the direction returned by this method.- Returns:
- The direction you need to move from
t1
in order to reacht2
, or null if the two specified tiles are not neighbours.
-
getRoughDirection
public static Direction getRoughDirection(Tile src, Tile dst)
Get the approximate direction from one tile to another.- Parameters:
src
- The sourceTile
.dst
- The destinationTile
.- Returns:
- The approximate direction from source to direction, or null if source and destination are the same.
-
getAdjacentTile
public Tile getAdjacentTile(int x, int y, Direction direction)
Gets the adjacent tile in a given direction from the given coordinates.- Parameters:
x
- The x coordinate to work from.y
- The y coordinate to work from.direction
- TheDirection
to check.- Returns:
- The adjacent
Tile
in the specified direction, or null if invalid.
-
getAdjacentTile
public Tile getAdjacentTile(Tile tile, Direction direction)
Gets the adjacent tile in a given direction from a given tile.- Parameters:
tile
- The startingTile
.direction
- TheDirection
to check.- Returns:
- The adjacent
Tile
in the specified direction, or null if invalid.
-
getDistance
public int getDistance(Tile t1, Tile t2)
Gets the distance between two tiles.- Parameters:
t1
- The firstTile
.t2
- The secondTile
.- Returns:
- The distance between the tiles.
-
getClosestTile
public Tile getClosestTile(Tile tile, java.util.Collection<Tile> tiles)
Get the closest tile to a given one from a list of other tiles.- Parameters:
tile
- TheTile
to start from.tiles
- The list ofTile
s to check.- Returns:
- The closest tile found (may be null if the list is empty).
-
getRandomLandTile
public Tile getRandomLandTile(java.util.Random random)
Select a random land tile on the map.- Parameters:
random
- ARandom
number source.- Returns:
- A random land tile, or null if none found.
-
getTileSet
public java.util.Set<Tile> getTileSet(java.util.function.Predicate<Tile> predicate)
Get a list of all the tiles that match a predicate.- Parameters:
predicate
- ThePredicate
to check.- Returns:
- A
List
of all matchingTile
s.
-
getTileList
public java.util.List<Tile> getTileList(java.util.function.Predicate<Tile> predicate)
Get a list of all the tiles that match a predicate.- Parameters:
predicate
- ThePredicate
to check.- Returns:
- A
List
of all matchingTile
s.
-
forEachTile
public void forEachTile(java.util.function.Consumer<Tile> consumer)
Perform an action on each tile.- Parameters:
consumer
- TheConsumer
action to perform.
-
forEachTile
public void forEachTile(java.util.function.Predicate<Tile> predicate, java.util.function.Consumer<Tile> consumer)
Perform an action on each tile that matches a predicate.- Parameters:
predicate
- ThePredicate
to match.consumer
- TheConsumer
action to perform.
-
populateTiles
public boolean populateTiles(java.util.function.BiFunction<java.lang.Integer,java.lang.Integer,Tile> func)
Populate the map. To be called to build a new map.- Parameters:
func
- AFunction
that makes a newTile
for the supplied x,y coordinates.- Returns:
- True if the map was populated.
-
forSubMap
public void forSubMap(int x, int y, int w, int h, java.util.function.Consumer<Tile> consumer)
Iterates through a rectangular subpart of the Map. Intentionally avoids calling methods doing redundant checks, which would slow down map display.- Parameters:
x
- X-component of the position of first tile.y
- Y-component of the position of first tile.w
- Width of the rectangle.h
- Height of the rectangle.consumer
- Provides a function to call for each tile.
-
subMap
public java.util.List<Tile> subMap(int x, int y, int w, int h)
Collect the tiles in a rectangular portion of the map.- Parameters:
x
- X-component of the position of first tile.y
- Y-component of the position of first tile.w
- Width of the rectangle.h
- Height of the rectangle.- Returns:
- A list of
Tile
s found (empty on error).
-
getShuffledTiles
public java.util.List<Tile> getShuffledTiles(java.util.Random random)
Get a shuffled list of all the tiles.- Parameters:
random
- A pseudo-random number source.- Returns:
- A shuffled list of all the
Tile
s in this map.
-
getCircleIterator
public java.util.Iterator<Tile> getCircleIterator(Tile center, boolean isFilled, int radius)
Gets a circle iterator.- Parameters:
center
- The centerTile
to iterate around.isFilled
- True to get all of the positions in the circle.radius
- The radius of circle.- Returns:
- The circle iterator.
-
getCircleTiles
public java.lang.Iterable<Tile> getCircleTiles(Tile center, boolean isFilled, int radius)
Gets an iterable for all the tiles in a circle using an underlying CircleIterator.- Parameters:
center
- The centerTile
to iterate around.isFilled
- True to get all of the positions in the circle.radius
- The radius of circle.- Returns:
- An
Iterable
for a circle of tiles.
-
getManhattenHeuristic
private Map.SearchHeuristic getManhattenHeuristic(Tile endTile)
Gets a search heuristic using the Manhatten distance to an end tile.- Parameters:
endTile
- TheTile
to aim for.- Returns:
- A new
SearchHeuristic
aiming for the end tile.
-
findRealEnd
private Location findRealEnd(Unit unit, Location end)
Destination argument test for path searches. Find the actual destination of a path.- Parameters:
unit
- An optionalUnit
to search for.end
- The candidate endLocation
.- Returns:
- The actual end location.
-
getBestEntryPath
private PathNode getBestEntryPath(Unit unit, Tile tile, Unit carrier, CostDecider costDecider)
Gets the best (closest) path location for this unit to reach a given tile from off the map.- Parameters:
unit
- TheUnit
to check.tile
- The targetTile
.carrier
- An optional carrierUnit
to use.costDecider
- An optionalCostDecider
to use.- Returns:
- A path to the best entry location tile to arrive on the map at, or null if none found.
-
getBestEntryTile
public Tile getBestEntryTile(Unit unit, Tile tile, Unit carrier, CostDecider costDecider)
Gets the best (closest) entry location for this unit to reach a given tile from off the map.- Parameters:
unit
- TheUnit
to check.tile
- The targetTile
.carrier
- An optional carrierUnit
to use.costDecider
- An optionalCostDecider
to use.- Returns:
- The best entry location tile to arrive on the map at, or null if none found.
-
findMapPath
private PathNode findMapPath(Unit unit, Tile start, Tile end, Unit carrier, CostDecider costDecider, LogBuilder lb)
Find the quickest path for a unit (with optional carrier) from a start tile to an end tile.- Parameters:
unit
- TheUnit
to find the path for.start
- TheTile
in which the path starts from.end
- TheTile
at the end of the path.carrier
- An optional naval carrierUnit
to use.costDecider
- An optionalCostDecider
for determining the movement costs (uses default cost deciders for the unit/s if not provided).lb
- An optionalLogBuilder
to log to.- Returns:
- A path starting at the start tile and ending at the end tile, or null if none found.
-
finishPath
private void finishPath(PathNode path, Unit unit, LogBuilder lb)
Finish processing a path.- Parameters:
path
- ThePathNode
to finish.unit
- TheUnit
that is travelling along the path.lb
- An optionalLogBuilder
to log to.
-
findPath
public PathNode findPath(Unit unit, Location start, Location end, Unit carrier, CostDecider costDecider, LogBuilder lb)
Find the quickest path for a unit (with optional carrier) from a start location to an end location.- Parameters:
unit
- TheUnit
to find the path for.start
- TheLocation
in which the path starts from.end
- TheLocation
at the end of the path.carrier
- An optional naval carrierUnit
to use.costDecider
- An optionalCostDecider
for determining the movement costs (uses default cost deciders for the unit/s if not provided).lb
- An optionalLogBuilder
to log to.- Returns:
- A path starting at the start location and ending at the end location, or null if none found.
-
search
public PathNode search(Unit unit, Location start, GoalDecider goalDecider, CostDecider costDecider, int maxTurns, Unit carrier, LogBuilder lb)
Searches for a goal. Assumes units in Europe return to their current entry location, which is not optimal most of the time. Returns the full path including the start and end locations.- Parameters:
unit
- TheUnit
to find a path for.start
- TheLocation
to start the search from.goalDecider
- The object responsible for determining whether a givenPathNode
is a goal or not.costDecider
- An optionalCostDecider
responsible for determining the path cost.maxTurns
- The maximum number of turns the givenUnit
is allowed to move. This is the maximum search range for a goal.carrier
- An optional naval carrierUnit
to use.lb
- An optionalLogBuilder
to log to.- Returns:
- The path to a goal, or null if none can be found.
- Throws:
java.lang.IllegalArgumentException
- If the unit is null, or the start location does not make sense, or the carrier/unit combination is bogus.
-
getSearchTrace
public boolean getSearchTrace()
Gets the search tracing status.- Returns:
- The search tracing status.
-
setSearchTrace
public boolean setSearchTrace(boolean trace)
Sets the search tracing status.- Parameters:
trace
- The new search tracing status.- Returns:
- The original search tracing status.
-
usedCarrier
private boolean usedCarrier(PathNode path)
Was a carrier used previously on a path? Beware! This is special case code for partially constructed paths that do not yet have valid .next links, so we can not use the generic PathNode routines.- Parameters:
path
- The path the search.- Returns:
- True if the path includes a previous on-carrier node.
-
searchMap
private PathNode searchMap(Unit unit, Tile start, GoalDecider goalDecider, CostDecider costDecider, int maxTurns, Unit carrier, Map.SearchHeuristic searchHeuristic, LogBuilder lb)
Searches for a path to a goal determined by the givenGoalDecider
. Using A* with a List (closedMap) for marking the visited nodes and using a PriorityQueue (openMapQueue) 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. If the SearchHeuristic is not supplied, then the algorithm degrades gracefully to Dijkstra's algorithm. 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.- Parameters:
unit
- TheUnit
to find a path for.start
- TheTile
to start the search from.goalDecider
- The object responsible for determining whether a givenPathNode
is a goal or not.costDecider
- An optionalCostDecider
responsible for determining the path cost.maxTurns
- The maximum number of turns the givenUnit
is allowed to move. This is the maximum search range for a goal.carrier
- An optional naval carrierUnit
to use.searchHeuristic
- An optionalSearchHeuristic
.lb
- An optionalLogBuilder
to log to.- Returns:
- A path to a goal determined by the given
GoalDecider
.
-
searchCircle
public Tile searchCircle(Tile start, GoalDecider goalDecider, int radius)
Searches for a tile within a radius of a starting tile. Does not use a unit, and thus does not consider movement validity.- Parameters:
start
- The startingTile
.goalDecider
- AGoalDecider
that chooses the goal, which must be capable of tolerating a null unit.radius
- The maximum radius of tiles to search from the start.- Returns:
- The goal tile as determined by the, or null if none found.
-
getLandWithinDistance
public Tile getLandWithinDistance(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 in tiles that should be searched for land.- Returns:
- The first land tile found within the radius, or null if none found.
-
floodFillBool
public static boolean[][] floodFillBool(boolean[][] boolmap, int x, int y)
Flood fills from a givenPosition
p, based on connectivity information encoded in boolmap- Parameters:
boolmap
- The connectivity information for this floodfill.x
- The starting x coordinate.y
- The starting y coordinate.- Returns:
- A boolean[][] of the same size as boolmap, where "true" means the fill succeeded at that location.
-
floodFillBool
public static boolean[][] floodFillBool(boolean[][] boolmap, int x, int y, int limit)
Flood fills from a givenPosition
p, based on connectivity information encoded in boolmap- Parameters:
boolmap
- The connectivity information for this floodfill.x
- The starting x coordinate.y
- The starting y coordinate.limit
- Limit to stop flood fill at.- Returns:
- A boolean[][] of the same size as boolmap, where "true" means the fill succeeded at that location.
-
resetContiguity
public void resetContiguity()
Sets the contiguity identifier for all tiles.
-
floodFill
private void floodFill(int contig, int ymax, int xmax, boolean[][] waterMap)
Performs fill flood action and calculations- Parameters:
contig
- The contiguity number.ymax
- The Y-valuexmax
- The X-valuewaterMap
- The boolean array containing the x and y coordinates
-
collectStartingTiles
public void collectStartingTiles(java.util.List<Tile> eastTiles, java.util.List<Tile> westTiles)
Collect lists of valid starting tiles on this map. Called from the map generator to help choose starting tiles for European units.- Parameters:
eastTiles
- A list ofTile
s on the east of the map to fill in.westTiles
- A list ofTile
s on the west of the map to fill in.
-
resetHighSeas
public void resetHighSeas(int distToLandFromHighSeas, int maxDistanceToEdge)
Places the "high seas"-tiles on the border of this map. All other tiles previously of type High Seas will be set to Ocean.- Parameters:
distToLandFromHighSeas
- The distance between the land and the high seas (given in tiles).maxDistanceToEdge
- The maximum distance a high sea tile can have from the edge of the map.
-
resetHighSeasCount
public void resetHighSeasCount()
Sets the high seas count for all tiles connected to the high seas. Any ocean tiles on the map vertical edges that do not have an explicit false moveToEurope attribute are given a true one. Set all high seas counts negative, then start with a count of zero for tiles with the moveToEurope attribute or of a type with that ability. Iterate outward by neighbouring tile, incrementing the count on each pass, stopping at land. Thus, only the coastal land tiles will have a non-negative high seas count. This significantly speeds up the colony site evaluator, as it does not have to try to find a path to Europe for each tile.
-
resetLayers
public void resetLayers()
Reset layer to reflect what is actually there.
-
fixupRegions
public void fixupRegions()
Fix the region parent/child relationships.
-
importTile
public Tile importTile(Tile other, int x, int y, Map.Layer layer)
Import a tile, possibly from another game.- Parameters:
other
- TheTile
to import.x
- The x-coordinate of the new tile.y
- The y-coordinate of the new tile.layer
- The maximum layer to import.- Returns:
- The new imported
Tile
.
-
scale
public Map scale(int width, int height)
Scale the map into the specified size. This implementation uses a simple linear scaling, and the isometric shape is not taken into account. FIXME: Find a better method for choosing a group of adjacent tiles. This group can then be merged into a common tile by using the average value (for example: are there a majority of ocean tiles?).- Parameters:
width
- The width of the resulting map.height
- The height of the resulting map.- Returns:
- A scaled version of this map.
-
getTile
public Tile getTile()
Gets the location tile. Obviously not applicable to a Map.
-
getLocationLabel
public StringTemplate getLocationLabel()
Get a label for this location.- Specified by:
getLocationLabel
in interfaceLocation
- Returns:
- A label for this location.
-
getLocationLabelFor
public StringTemplate getLocationLabelFor(Player player)
Get a label for this location for a particular player.- Specified by:
getLocationLabelFor
in interfaceLocation
- Parameters:
player
- ThePlayer
to return the name for.- Returns:
- A label for this location.
-
add
public boolean add(Locatable locatable)
Adds aLocatable
to this Location.
-
remove
public boolean remove(Locatable locatable)
Removes aLocatable
from this Location.
-
contains
public boolean contains(Locatable locatable)
Checks if thisLocation
contains the specifiedLocatable
.
-
canAdd
public boolean canAdd(Locatable locatable)
Checks whether or not the specified locatable may be added to thisLocation
.
-
getUnitCount
public int getUnitCount()
Gets the number of units at this Location.- Specified by:
getUnitCount
in interfaceLocation
- Returns:
- The number of units at this Location.
-
getUnits
public java.util.stream.Stream<Unit> getUnits()
Gets a stream of all the units present at this location.
-
getUnitList
public java.util.List<Unit> getUnitList()
Gets a list of all the units present at this location.- Specified by:
getUnitList
in interfaceLocation
- Returns:
- A list of all the units at this location.
-
getGoodsContainer
public GoodsContainer getGoodsContainer()
Gets theGoodsContainer
thisLocation
use for storing it's goods.- Specified by:
getGoodsContainer
in interfaceLocation
- Returns:
- The
GoodsContainer
ornull
if theLocation
cannot store any goods.
-
getSettlement
public Settlement getSettlement()
Gets theSettlement
thisLocation
is located in.- Specified by:
getSettlement
in interfaceLocation
- Returns:
- The associated
Settlement
, or null if none.
-
getColony
public Colony getColony()
Get the colony at this location.
-
getIndianSettlement
public IndianSettlement getIndianSettlement()
Gets the native settlement at this location.- Specified by:
getIndianSettlement
in interfaceLocation
- Returns:
- The
IndianSettlement
at this location if any, or null if none found.
-
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:
toShortString
in interfaceLocation
- Returns:
- A short description.
-
getLocationImageKey
public java.lang.String getLocationImageKey()
Get an image key for this location.- Specified by:
getLocationImageKey
in interfaceLocation
- Returns:
- A key for image lookup, null by default.
-
checkIntegrity
public Constants.IntegrityType checkIntegrity(boolean fix, LogBuilder lb)
Checks the integrity of this game object.- Overrides:
checkIntegrity
in classFreeColGameObject
- Parameters:
fix
- If true, fix problems if possible.lb
- ALogBuilder
to log to.- Returns:
- A suitable
IntegrityType
.
-
copyIn
public <T extends FreeColObject> boolean copyIn(T other)
Copy another FreeColObject into this one if it is compatible.- Overrides:
copyIn
in classFreeColGameObject
- Type Parameters:
T
- TheFreeColObject
subclass of the object to copy in.- Parameters:
other
- The other object.- Returns:
- True if the copy in is succesful.
-
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:
writeAttributes
in classFreeColObject
- Parameters:
xw
- TheFreeColXMLWriter
to 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:
writeChildren
in classFreeColObject
- Parameters:
xw
- TheFreeColXMLWriter
to 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:
readAttributes
in classFreeColGameObject
- Parameters:
xr
- TheFreeColXMLReader
to 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:
readChildren
in classFreeColObject
- Parameters:
xr
- TheFreeColXMLReader
to 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:
readChild
in classFreeColObject
- Parameters:
xr
- TheFreeColXMLReader
to 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:
getXMLTagName
in classFreeColObject
- Returns:
- The tag.
-
-