I have a 2D tile-based strategy in the works. I'm wandering how to handle the relationship between the map and the units on the map.
Given a tile coordinate I'll need to be able to get the unit standing on it, if any. At the same time, if given a unit I'll want to be able to get the unit's coordinate.
I've seen two solutions to this. The first solution would be to have units store a coordinate and the map store unit references in its tiles. This creates a cyclic dependency between the map and units. I'd need to make sure that the map an any unit are kept in sync if the unit moves.
The second solution would be to only have the units keep track of their coordinates. To tell if a tile contains a unit and to get that unit, I'd loop through the whole set of units unit I find one with matching coordinates. That get rids of the cyclic dependency, but it looses the O(1) property the first solution had for looking up units from the map. This may add up as I want to be able to scan the map regularly for things such as path finding, determining movement range, and finding valid targets for a given unit.
I also can't just store the units in the map (or can I?). Units are associated with "armies", either player or AI. An army should be able to easily access and iterate over all of its units.
Since this appears to be a common issue in strategy games, are there any other patterns besides the two I described for managing unit/map relationships?