2
0

StupidAI.cpp 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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(void)
  18. : side(-1)
  19. {
  20. print("created");
  21. }
  22. CStupidAI::~CStupidAI(void)
  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(CRandomGenerator::getDefault(), ourStack, s, &retal);
  49. adi = (dmg.first + dmg.second) / 2;
  50. adr = (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. namespace {
  62. int distToNearestNeighbour(BattleHex hex, const ReachabilityInfo::TDistances& dists, BattleHex *chosenHex = nullptr)
  63. {
  64. int ret = 1000000;
  65. for(auto & n: hex.neighbouringTiles())
  66. {
  67. if(dists[n] >= 0 && dists[n] < ret)
  68. {
  69. ret = dists[n];
  70. if(chosenHex)
  71. *chosenHex = n;
  72. }
  73. }
  74. return ret;
  75. }
  76. bool isCloser(const EnemyInfo & ei1, const EnemyInfo & ei2, const ReachabilityInfo::TDistances & dists)
  77. {
  78. return distToNearestNeighbour(ei1.s->position, dists) < distToNearestNeighbour(ei2.s->position, dists);
  79. }
  80. }
  81. static bool willSecondHexBlockMoreEnemyShooters(const BattleHex &h1, const BattleHex &h2)
  82. {
  83. int shooters[2] = {0}; //count of shooters on hexes
  84. for(int i = 0; i < 2; i++)
  85. for (auto & neighbour : (i ? h2 : h1).neighbouringTiles())
  86. if(const CStack *s = cbc->battleGetStackByPos(neighbour))
  87. if(s->getCreature()->isShooting())
  88. shooters[i]++;
  89. return shooters[0] < shooters[1];
  90. }
  91. BattleAction CStupidAI::activeStack( const CStack * stack )
  92. {
  93. //boost::this_thread::sleep(boost::posix_time::seconds(2));
  94. print("activeStack called for " + stack->nodeName());
  95. auto dists = cb->battleGetDistances(stack);
  96. std::vector<EnemyInfo> enemiesShootable, enemiesReachable, enemiesUnreachable;
  97. if(stack->type->idNumber == CreatureID::CATAPULT)
  98. {
  99. BattleAction attack;
  100. static const std::vector<int> wallHexes = {50, 183, 182, 130, 78, 29, 12, 95};
  101. attack.destinationTile = *RandomGeneratorUtil::nextItem(wallHexes, CRandomGenerator::getDefault());
  102. attack.actionType = Battle::CATAPULT;
  103. attack.additionalInfo = 0;
  104. attack.side = side;
  105. attack.stackNumber = stack->ID;
  106. return attack;
  107. }
  108. else if(stack->hasBonusOfType(Bonus::SIEGE_WEAPON))
  109. {
  110. return BattleAction::makeDefend(stack);
  111. }
  112. for (const CStack *s : cb->battleGetStacks(CBattleCallback::ONLY_ENEMY))
  113. {
  114. if(cb->battleCanShoot(stack, s->position))
  115. {
  116. enemiesShootable.push_back(s);
  117. }
  118. else
  119. {
  120. std::vector<BattleHex> avHexes = cb->battleGetAvailableHexes(stack, false);
  121. for (BattleHex hex : avHexes)
  122. {
  123. if(CStack::isMeleeAttackPossible(stack, s, hex))
  124. {
  125. std::vector<EnemyInfo>::iterator i = std::find(enemiesReachable.begin(), enemiesReachable.end(), s);
  126. if(i == enemiesReachable.end())
  127. {
  128. enemiesReachable.push_back(s);
  129. i = enemiesReachable.begin() + (enemiesReachable.size() - 1);
  130. }
  131. i->attackFrom.push_back(hex);
  132. }
  133. }
  134. if(!vstd::contains(enemiesReachable, s) && s->position.isValid())
  135. enemiesUnreachable.push_back(s);
  136. }
  137. }
  138. for ( auto & enemy : enemiesReachable )
  139. enemy.calcDmg( stack );
  140. for ( auto & enemy : enemiesShootable )
  141. enemy.calcDmg( stack );
  142. if(enemiesShootable.size())
  143. {
  144. const EnemyInfo &ei= *std::max_element(enemiesShootable.begin(), enemiesShootable.end(), isMoreProfitable);
  145. return BattleAction::makeShotAttack(stack, ei.s);
  146. }
  147. else if(enemiesReachable.size())
  148. {
  149. const EnemyInfo &ei= *std::max_element(enemiesReachable.begin(), enemiesReachable.end(), &isMoreProfitable);
  150. return BattleAction::makeMeleeAttack(stack, ei.s, *std::max_element(ei.attackFrom.begin(), ei.attackFrom.end(), &willSecondHexBlockMoreEnemyShooters));
  151. }
  152. else if(enemiesUnreachable.size()) //due to #955 - a buggy battle may occur when there are no enemies
  153. {
  154. assert(enemiesUnreachable.size());
  155. const EnemyInfo &ei= *std::min_element(enemiesUnreachable.begin(), enemiesUnreachable.end(), std::bind(isCloser, _1, _2, std::ref(dists)));
  156. assert(ei.s);
  157. if(distToNearestNeighbour(ei.s->position, dists) < GameConstants::BFIELD_SIZE)
  158. {
  159. return goTowards(stack, ei.s->position);
  160. }
  161. }
  162. return BattleAction::makeDefend(stack);
  163. }
  164. void CStupidAI::battleAttack(const BattleAttack *ba)
  165. {
  166. print("battleAttack called");
  167. }
  168. void CStupidAI::battleStacksAttacked(const std::vector<BattleStackAttacked> & bsa)
  169. {
  170. print("battleStacksAttacked called");
  171. }
  172. void CStupidAI::battleEnd(const BattleResult *br)
  173. {
  174. print("battleEnd called");
  175. }
  176. // void CStupidAI::battleResultsApplied()
  177. // {
  178. // print("battleResultsApplied called");
  179. // }
  180. void CStupidAI::battleNewRoundFirst(int round)
  181. {
  182. print("battleNewRoundFirst called");
  183. }
  184. void CStupidAI::battleNewRound(int round)
  185. {
  186. print("battleNewRound called");
  187. }
  188. void CStupidAI::battleStackMoved(const CStack * stack, std::vector<BattleHex> dest, int distance)
  189. {
  190. print("battleStackMoved called");
  191. }
  192. void CStupidAI::battleSpellCast(const BattleSpellCast *sc)
  193. {
  194. print("battleSpellCast called");
  195. }
  196. void CStupidAI::battleStacksEffectsSet(const SetStackEffect & sse)
  197. {
  198. print("battleStacksEffectsSet called");
  199. }
  200. void CStupidAI::battleStart(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool Side)
  201. {
  202. print("battleStart called");
  203. side = Side;
  204. }
  205. void CStupidAI::battleStacksHealedRes(const std::vector<std::pair<ui32, ui32> > & healedStacks, bool lifeDrain, bool tentHeal, si32 lifeDrainFrom)
  206. {
  207. print("battleStacksHealedRes called");
  208. }
  209. void CStupidAI::battleNewStackAppeared(const CStack * stack)
  210. {
  211. print("battleNewStackAppeared called");
  212. }
  213. void CStupidAI::battleObstaclesRemoved(const std::set<si32> & removedObstacles)
  214. {
  215. print("battleObstaclesRemoved called");
  216. }
  217. void CStupidAI::battleCatapultAttacked(const CatapultAttack & ca)
  218. {
  219. print("battleCatapultAttacked called");
  220. }
  221. void CStupidAI::battleStacksRemoved(const BattleStacksRemoved & bsr)
  222. {
  223. print("battleStacksRemoved called");
  224. }
  225. void CStupidAI::print(const std::string &text) const
  226. {
  227. logAi->trace("CStupidAI [%p]: %s", this, text);
  228. }
  229. BattleAction CStupidAI::goTowards(const CStack * stack, BattleHex destination)
  230. {
  231. assert(destination.isValid());
  232. auto avHexes = cb->battleGetAvailableHexes(stack, false);
  233. auto reachability = cb->getReachability(stack);
  234. if(vstd::contains(avHexes, destination))
  235. return BattleAction::makeMove(stack, destination);
  236. auto destNeighbours = destination.neighbouringTiles();
  237. if(vstd::contains_if(destNeighbours, [&](BattleHex n) { return stack->coversPos(destination); }))
  238. {
  239. logAi->warn("Warning: already standing on neighbouring tile!");
  240. //We shouldn't even be here...
  241. return BattleAction::makeDefend(stack);
  242. }
  243. vstd::erase_if(destNeighbours, [&](BattleHex hex){ return !reachability.accessibility.accessible(hex, stack); });
  244. if(!avHexes.size() || !destNeighbours.size()) //we are blocked or dest is blocked
  245. {
  246. print("goTowards: Stack cannot move! That's " + stack->nodeName());
  247. return BattleAction::makeDefend(stack);
  248. }
  249. if(stack->hasBonusOfType(Bonus::FLYING))
  250. {
  251. // Flying stack doesn't go hex by hex, so we can't backtrack using predecessors.
  252. // We just check all available hexes and pick the one closest to the target.
  253. auto distToDestNeighbour = [&](BattleHex hex) -> int
  254. {
  255. auto nearestNeighbourToHex = vstd::minElementByFun(destNeighbours, [&](BattleHex a)
  256. {
  257. return BattleHex::getDistance(a, hex);
  258. });
  259. return BattleHex::getDistance(*nearestNeighbourToHex, hex);
  260. };
  261. auto nearestAvailableHex = vstd::minElementByFun(avHexes, distToDestNeighbour);
  262. return BattleAction::makeMove(stack, *nearestAvailableHex);
  263. }
  264. else
  265. {
  266. BattleHex bestNeighbor = destination;
  267. if(distToNearestNeighbour(destination, reachability.distances, &bestNeighbor) > GameConstants::BFIELD_SIZE)
  268. {
  269. print("goTowards: Cannot reach");
  270. return BattleAction::makeDefend(stack);
  271. }
  272. BattleHex currentDest = bestNeighbor;
  273. while(1)
  274. {
  275. assert(currentDest.isValid());
  276. if(vstd::contains(avHexes, currentDest))
  277. return BattleAction::makeMove(stack, currentDest);
  278. currentDest = reachability.predecessors[currentDest];
  279. }
  280. }
  281. }
  282. void CStupidAI::saveGame(BinarySerializer & h, const int version)
  283. {
  284. //TODO to be implemented with saving/loading during the battles
  285. assert(0);
  286. }
  287. void CStupidAI::loadGame(BinaryDeserializer & h, const int version)
  288. {
  289. //TODO to be implemented with saving/loading during the battles
  290. assert(0);
  291. }