2
0

StupidAI.cpp 9.2 KB

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