BattleHex.cpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /*
  2. * BattleHex.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "BattleHex.h"
  12. #include "BattleHexArray.h"
  13. VCMI_LIB_NAMESPACE_BEGIN
  14. BattleHex BattleHex::getClosestTile(BattleSide side, const BattleHex & initialPos, const BattleHexArray & hexes)
  15. {
  16. if(hexes.empty())
  17. return BattleHex();
  18. BattleHex initialHex = BattleHex(initialPos);
  19. int closestDistance = std::numeric_limits<int>::max();
  20. BattleHexArray closestTiles;
  21. for(const auto & hex : hexes)
  22. {
  23. int distance = initialHex.getDistance(initialHex, hex);
  24. if(distance < closestDistance)
  25. {
  26. closestDistance = distance;
  27. closestTiles.clear();
  28. closestTiles.insert(hex);
  29. }
  30. else if(distance == closestDistance)
  31. closestTiles.insert(hex);
  32. }
  33. auto compareHorizontal = [side, initialPos](const BattleHex & left, const BattleHex & right)
  34. {
  35. if(left.getX() != right.getX())
  36. {
  37. return (side == BattleSide::ATTACKER) ? (left.getX() > right.getX()) : (left.getX() < right.getX());
  38. }
  39. return std::abs(left.getY() - initialPos.getY()) < std::abs(right.getY() - initialPos.getY());
  40. };
  41. auto bestTile = std::min_element(closestTiles.begin(), closestTiles.end(), compareHorizontal);
  42. return (bestTile != closestTiles.end()) ? *bestTile : BattleHex();
  43. }
  44. const BattleHexArray & BattleHex::getAllNeighbouringTiles() const noexcept
  45. {
  46. return BattleHexArray::getAllNeighbouringTiles(*this);
  47. }
  48. const BattleHexArray & BattleHex::getNeighbouringTiles() const noexcept
  49. {
  50. return BattleHexArray::getNeighbouringTiles(*this);
  51. }
  52. const BattleHexArray & BattleHex::getNeighbouringTilesDoubleWide(BattleSide side) const noexcept
  53. {
  54. return BattleHexArray::getNeighbouringTilesDoubleWide(*this, side);
  55. }
  56. std::ostream & operator<<(std::ostream & os, const BattleHex & hex)
  57. {
  58. return os << hex.toInt();
  59. }
  60. VCMI_LIB_NAMESPACE_END