BattleHex.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #include "StdInc.h"
  2. #include "BattleHex.h"
  3. void BattleHex::operator+=(EDir dir)
  4. {
  5. si16 x = getX(),
  6. y = getY();
  7. switch(dir)
  8. {
  9. case TOP_LEFT:
  10. setXY(y%2 ? x-1 : x, y-1);
  11. break;
  12. case TOP_RIGHT:
  13. setXY(y%2 ? x : x+1, y-1);
  14. break;
  15. case RIGHT:
  16. setXY(x+1, y);
  17. break;
  18. case BOTTOM_RIGHT:
  19. setXY(y%2 ? x : x+1, y+1);
  20. break;
  21. case BOTTOM_LEFT:
  22. setXY(y%2 ? x-1 : x, y+1);
  23. break;
  24. case LEFT:
  25. setXY(x-1, y);
  26. break;
  27. default:
  28. throw std::string("Disaster: wrong direction in BattleHex::operator+=!\n");
  29. break;
  30. }
  31. }
  32. BattleHex BattleHex::operator+(EDir dir) const
  33. {
  34. BattleHex ret(*this);
  35. ret += dir;
  36. return ret;
  37. }
  38. std::vector<BattleHex> BattleHex::neighbouringTiles() const
  39. {
  40. std::vector<BattleHex> ret;
  41. const int WN = GameConstants::BFIELD_WIDTH;
  42. checkAndPush(hex - ( (hex/WN)%2 ? WN+1 : WN ), ret);
  43. checkAndPush(hex - ( (hex/WN)%2 ? WN : WN-1 ), ret);
  44. checkAndPush(hex - 1, ret);
  45. checkAndPush(hex + 1, ret);
  46. checkAndPush(hex + ( (hex/WN)%2 ? WN-1 : WN ), ret);
  47. checkAndPush(hex + ( (hex/WN)%2 ? WN : WN+1 ), ret);
  48. return ret;
  49. }
  50. signed char BattleHex::mutualPosition(BattleHex hex1, BattleHex hex2)
  51. {
  52. if(hex2 == hex1 - ( (hex1/17)%2 ? 18 : 17 )) //top left
  53. return 0;
  54. if(hex2 == hex1 - ( (hex1/17)%2 ? 17 : 16 )) //top right
  55. return 1;
  56. if(hex2 == hex1 - 1 && hex1%17 != 0) //left
  57. return 5;
  58. if(hex2 == hex1 + 1 && hex1%17 != 16) //right
  59. return 2;
  60. if(hex2 == hex1 + ( (hex1/17)%2 ? 16 : 17 )) //bottom left
  61. return 4;
  62. if(hex2 == hex1 + ( (hex1/17)%2 ? 17 : 18 )) //bottom right
  63. return 3;
  64. return -1;
  65. }
  66. char BattleHex::getDistance(BattleHex hex1, BattleHex hex2)
  67. {
  68. int xDst = std::abs(hex1 % GameConstants::BFIELD_WIDTH - hex2 % GameConstants::BFIELD_WIDTH),
  69. yDst = std::abs(hex1 / GameConstants::BFIELD_WIDTH - hex2 / GameConstants::BFIELD_WIDTH);
  70. return std::max(xDst, yDst) + std::min(xDst, yDst) - (yDst + 1)/2;
  71. }
  72. void BattleHex::checkAndPush(int tile, std::vector<BattleHex> & ret)
  73. {
  74. if( tile>=0 && tile<GameConstants::BFIELD_SIZE && (tile%GameConstants::BFIELD_WIDTH != (GameConstants::BFIELD_WIDTH - 1))
  75. && (tile%GameConstants::BFIELD_WIDTH != 0) )
  76. ret.push_back(BattleHex(tile));
  77. }
  78. bool BattleHex::isAvailable() const
  79. {
  80. return isValid() && getX() > 0 && getX() < GameConstants::BFIELD_WIDTH-1;
  81. }