StupidAI.cpp 8.3 KB

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