StupidAI.cpp 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. /*
  2. * StupidAI.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 "../../lib/AI_Base.h"
  12. #include "StupidAI.h"
  13. #include "../../lib/CStack.h"
  14. #include "../../CCallback.h"
  15. #include "../../lib/CCreatureHandler.h"
  16. static std::shared_ptr<CBattleCallback> cbc;
  17. CStupidAI::CStupidAI()
  18. : side(-1)
  19. {
  20. print("created");
  21. }
  22. CStupidAI::~CStupidAI()
  23. {
  24. print("destroyed");
  25. }
  26. void CStupidAI::init(std::shared_ptr<CBattleCallback> CB)
  27. {
  28. print("init called, saving ptr to IBattleCallback");
  29. cbc = cb = CB;
  30. }
  31. void CStupidAI::actionFinished(const BattleAction &action)
  32. {
  33. print("actionFinished called");
  34. }
  35. void CStupidAI::actionStarted(const BattleAction &action)
  36. {
  37. print("actionStarted called");
  38. }
  39. struct EnemyInfo
  40. {
  41. const CStack * s;
  42. int adi, adr;
  43. std::vector<BattleHex> attackFrom; //for melee fight
  44. EnemyInfo(const CStack * _s) : s(_s), adi(0), adr(0)
  45. {}
  46. void calcDmg(const CStack * ourStack)
  47. {
  48. TDmgRange retal, dmg = cbc->battleEstimateDamage(ourStack, s, &retal);
  49. adi = static_cast<int>((dmg.first + dmg.second) / 2);
  50. adr = static_cast<int>((retal.first + retal.second) / 2);
  51. }
  52. bool operator==(const EnemyInfo& ei) const
  53. {
  54. return s == ei.s;
  55. }
  56. };
  57. bool isMoreProfitable(const EnemyInfo &ei1, const EnemyInfo& ei2)
  58. {
  59. return (ei1.adi-ei1.adr) < (ei2.adi - ei2.adr);
  60. }
  61. static bool willSecondHexBlockMoreEnemyShooters(const BattleHex &h1, const BattleHex &h2)
  62. {
  63. int shooters[2] = {0}; //count of shooters on hexes
  64. for(int i = 0; i < 2; i++)
  65. for (auto & neighbour : (i ? h2 : h1).neighbouringTiles())
  66. if(const CStack *s = cbc->battleGetStackByPos(neighbour))
  67. if(s->getCreature()->isShooting())
  68. shooters[i]++;
  69. return shooters[0] < shooters[1];
  70. }
  71. BattleAction CStupidAI::activeStack( const CStack * stack )
  72. {
  73. //boost::this_thread::sleep(boost::posix_time::seconds(2));
  74. print("activeStack called for " + stack->nodeName());
  75. ReachabilityInfo dists = cb->getReachability(stack);
  76. std::vector<EnemyInfo> enemiesShootable, enemiesReachable, enemiesUnreachable;
  77. if(stack->type->idNumber == CreatureID::CATAPULT)
  78. {
  79. BattleAction attack;
  80. static const std::vector<int> wallHexes = {50, 183, 182, 130, 78, 29, 12, 95};
  81. auto seletectedHex = *RandomGeneratorUtil::nextItem(wallHexes, CRandomGenerator::getDefault());
  82. attack.aimToHex(seletectedHex);
  83. attack.actionType = EActionType::CATAPULT;
  84. attack.side = side;
  85. attack.stackNumber = stack->ID;
  86. return attack;
  87. }
  88. else if(stack->hasBonusOfType(Bonus::SIEGE_WEAPON))
  89. {
  90. return BattleAction::makeDefend(stack);
  91. }
  92. for (const CStack *s : cb->battleGetStacks(CBattleCallback::ONLY_ENEMY))
  93. {
  94. if(cb->battleCanShoot(stack, s->getPosition()))
  95. {
  96. enemiesShootable.push_back(s);
  97. }
  98. else
  99. {
  100. std::vector<BattleHex> avHexes = cb->battleGetAvailableHexes(stack);
  101. for (BattleHex hex : avHexes)
  102. {
  103. if(CStack::isMeleeAttackPossible(stack, s, hex))
  104. {
  105. std::vector<EnemyInfo>::iterator i = std::find(enemiesReachable.begin(), enemiesReachable.end(), s);
  106. if(i == enemiesReachable.end())
  107. {
  108. enemiesReachable.push_back(s);
  109. i = enemiesReachable.begin() + (enemiesReachable.size() - 1);
  110. }
  111. i->attackFrom.push_back(hex);
  112. }
  113. }
  114. if(!vstd::contains(enemiesReachable, s) && s->getPosition().isValid())
  115. enemiesUnreachable.push_back(s);
  116. }
  117. }
  118. for ( auto & enemy : enemiesReachable )
  119. enemy.calcDmg( stack );
  120. for ( auto & enemy : enemiesShootable )
  121. enemy.calcDmg( stack );
  122. if(enemiesShootable.size())
  123. {
  124. const EnemyInfo &ei= *std::max_element(enemiesShootable.begin(), enemiesShootable.end(), isMoreProfitable);
  125. return BattleAction::makeShotAttack(stack, ei.s);
  126. }
  127. else if(enemiesReachable.size())
  128. {
  129. const EnemyInfo &ei= *std::max_element(enemiesReachable.begin(), enemiesReachable.end(), &isMoreProfitable);
  130. return BattleAction::makeMeleeAttack(stack, ei.s->getPosition(), *std::max_element(ei.attackFrom.begin(), ei.attackFrom.end(), &willSecondHexBlockMoreEnemyShooters));
  131. }
  132. else if(enemiesUnreachable.size()) //due to #955 - a buggy battle may occur when there are no enemies
  133. {
  134. auto closestEnemy = vstd::minElementByFun(enemiesUnreachable, [&](const EnemyInfo & ei) -> int
  135. {
  136. return dists.distToNearestNeighbour(stack, ei.s);
  137. });
  138. if(dists.distToNearestNeighbour(stack, closestEnemy->s) < GameConstants::BFIELD_SIZE)
  139. {
  140. return goTowards(stack, closestEnemy->s);
  141. }
  142. }
  143. return BattleAction::makeDefend(stack);
  144. }
  145. void CStupidAI::battleAttack(const BattleAttack *ba)
  146. {
  147. print("battleAttack called");
  148. }
  149. void CStupidAI::battleStacksAttacked(const std::vector<BattleStackAttacked> & bsa, const std::vector<MetaString> & battleLog)
  150. {
  151. print("battleStacksAttacked called");
  152. }
  153. void CStupidAI::battleEnd(const BattleResult *br)
  154. {
  155. print("battleEnd called");
  156. }
  157. // void CStupidAI::battleResultsApplied()
  158. // {
  159. // print("battleResultsApplied called");
  160. // }
  161. void CStupidAI::battleNewRoundFirst(int round)
  162. {
  163. print("battleNewRoundFirst called");
  164. }
  165. void CStupidAI::battleNewRound(int round)
  166. {
  167. print("battleNewRound called");
  168. }
  169. void CStupidAI::battleStackMoved(const CStack * stack, std::vector<BattleHex> dest, int distance)
  170. {
  171. print("battleStackMoved called");
  172. }
  173. void CStupidAI::battleSpellCast(const BattleSpellCast *sc)
  174. {
  175. print("battleSpellCast called");
  176. }
  177. void CStupidAI::battleStacksEffectsSet(const SetStackEffect & sse)
  178. {
  179. print("battleStacksEffectsSet called");
  180. }
  181. void CStupidAI::battleStart(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool Side)
  182. {
  183. print("battleStart called");
  184. side = Side;
  185. }
  186. void CStupidAI::battleCatapultAttacked(const CatapultAttack & ca)
  187. {
  188. print("battleCatapultAttacked called");
  189. }
  190. void CStupidAI::print(const std::string &text) const
  191. {
  192. logAi->trace("CStupidAI [%p]: %s", this, text);
  193. }
  194. BattleAction CStupidAI::goTowards(const CStack * stack, const CStack * enemy) const
  195. {
  196. auto destination = enemy->getPosition();
  197. assert(destination.isValid());
  198. auto reachability = cb->getReachability(stack);
  199. auto avHexes = cb->battleGetAvailableHexes(reachability, stack);
  200. if(vstd::contains(avHexes, destination))
  201. return BattleAction::makeMove(stack, destination);
  202. auto destNeighbours = destination.neighbouringTiles();
  203. if(vstd::contains_if(destNeighbours, [&](BattleHex n) { return stack->coversPos(destination); }))
  204. {
  205. logAi->warn("Warning: already standing on neighbouring tile!");
  206. //We shouldn't even be here...
  207. return BattleAction::makeDefend(stack);
  208. }
  209. if(!avHexes.size()) //we are blocked or dest is blocked
  210. {
  211. return BattleAction::makeDefend(stack);
  212. }
  213. BattleHex bestNeighbor = destination;
  214. if(reachability.distToNearestNeighbour(stack, enemy, &bestNeighbor) > GameConstants::BFIELD_SIZE)
  215. {
  216. return BattleAction::makeDefend(stack);
  217. }
  218. if(stack->hasBonusOfType(Bonus::FLYING))
  219. {
  220. // Flying stack doesn't go hex by hex, so we can't backtrack using predecessors.
  221. // We just check all available hexes and pick the one closest to the target.
  222. auto nearestAvailableHex = vstd::minElementByFun(avHexes, [&](BattleHex hex) -> int
  223. {
  224. return BattleHex::getDistance(bestNeighbor, hex);
  225. });
  226. return BattleAction::makeMove(stack, *nearestAvailableHex);
  227. }
  228. else
  229. {
  230. BattleHex currentDest = bestNeighbor;
  231. while(1)
  232. {
  233. if(!currentDest.isValid())
  234. {
  235. logAi->error("CBattleAI::goTowards: internal error");
  236. return BattleAction::makeDefend(stack);
  237. }
  238. if(vstd::contains(avHexes, currentDest))
  239. return BattleAction::makeMove(stack, currentDest);
  240. currentDest = reachability.predecessors[currentDest];
  241. }
  242. }
  243. }
  244. void CStupidAI::saveGame(BinarySerializer & h, const int version)
  245. {
  246. //TODO to be implemented with saving/loading during the battles
  247. assert(0);
  248. }
  249. void CStupidAI::loadGame(BinaryDeserializer & h, const int version)
  250. {
  251. //TODO to be implemented with saving/loading during the battles
  252. assert(0);
  253. }