StupidAI.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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 "StupidAI.h"
  12. #include "../../lib/CStack.h"
  13. #include "../../lib/CCreatureHandler.h"
  14. #include "../../lib/battle/BattleAction.h"
  15. #include "../../lib/battle/BattleInfo.h"
  16. #include "../../lib/battle/CPlayerBattleCallback.h"
  17. #include "../../lib/callback/CBattleCallback.h"
  18. #include "../../lib/CRandomGenerator.h"
  19. CStupidAI::CStupidAI()
  20. : side(BattleSide::NONE)
  21. , wasWaitingForRealize(false)
  22. {
  23. print("created");
  24. }
  25. CStupidAI::~CStupidAI()
  26. {
  27. print("destroyed");
  28. if(cb)
  29. {
  30. //Restore previous state of CB - it may be shared with the main AI (like VCAI)
  31. cb->waitTillRealize = wasWaitingForRealize;
  32. }
  33. }
  34. void CStupidAI::initBattleInterface(std::shared_ptr<Environment> ENV, std::shared_ptr<CBattleCallback> CB)
  35. {
  36. print("init called, saving ptr to IBattleCallback");
  37. env = ENV;
  38. cb = CB;
  39. wasWaitingForRealize = CB->waitTillRealize;
  40. CB->waitTillRealize = false;
  41. }
  42. void CStupidAI::initBattleInterface(std::shared_ptr<Environment> ENV, std::shared_ptr<CBattleCallback> CB, AutocombatPreferences autocombatPreferences)
  43. {
  44. initBattleInterface(ENV, CB);
  45. }
  46. void CStupidAI::actionFinished(const BattleID & battleID, const BattleAction &action)
  47. {
  48. print("actionFinished called");
  49. }
  50. void CStupidAI::actionStarted(const BattleID & battleID, const BattleAction &action)
  51. {
  52. print("actionStarted called");
  53. }
  54. class EnemyInfo
  55. {
  56. public:
  57. const CStack * s;
  58. int adi;
  59. int adr;
  60. BattleHexArray attackFrom; //for melee fight
  61. EnemyInfo(const CStack * _s) : s(_s), adi(0), adr(0)
  62. {}
  63. void calcDmg(std::shared_ptr<CBattleCallback> cb, const BattleID & battleID, const CStack * ourStack)
  64. {
  65. // FIXME: provide distance info for Jousting bonus
  66. DamageEstimation retal;
  67. DamageEstimation dmg = cb->getBattle(battleID)->battleEstimateDamage(ourStack, s, 0, &retal);
  68. // Clip damage dealt to total stack health
  69. auto totalHealth = s->getTotalHealth();
  70. vstd::amin(dmg.damage.min, totalHealth);
  71. vstd::amin(dmg.damage.max, totalHealth);
  72. auto ourHealth = s->getTotalHealth();
  73. vstd::amin(retal.damage.min, ourHealth);
  74. vstd::amin(retal.damage.max, ourHealth);
  75. adi = static_cast<int>((dmg.damage.min + dmg.damage.max) / 2);
  76. adr = static_cast<int>((retal.damage.min + retal.damage.max) / 2);
  77. }
  78. bool operator==(const EnemyInfo& ei) const
  79. {
  80. return s == ei.s;
  81. }
  82. };
  83. bool isMoreProfitable(const EnemyInfo &ei1, const EnemyInfo& ei2)
  84. {
  85. return (ei1.adi-ei1.adr) < (ei2.adi - ei2.adr);
  86. }
  87. static bool willSecondHexBlockMoreEnemyShooters(std::shared_ptr<CBattleCallback> cb, const BattleID & battleID, const BattleHex &h1, const BattleHex &h2)
  88. {
  89. int shooters[2] = {0}; //count of shooters on hexes
  90. for(int i = 0; i < 2; i++)
  91. {
  92. BattleHex hex = i ? h2 : h1;
  93. for (auto neighbour : hex.getNeighbouringTiles())
  94. if(const auto * s = cb->getBattle(battleID)->battleGetUnitByPos(neighbour))
  95. if(s->isShooter())
  96. shooters[i]++;
  97. }
  98. return shooters[0] < shooters[1];
  99. }
  100. void CStupidAI::yourTacticPhase(const BattleID & battleID, int distance)
  101. {
  102. cb->battleMakeTacticAction(battleID, BattleAction::makeEndOFTacticPhase(cb->getBattle(battleID)->battleGetTacticsSide()));
  103. }
  104. void CStupidAI::activeStack(const BattleID & battleID, const CStack * stack)
  105. {
  106. print("activeStack called for " + stack->nodeName());
  107. ReachabilityInfo dists = cb->getBattle(battleID)->getReachability(stack);
  108. std::vector<EnemyInfo> enemiesShootable;
  109. std::vector<EnemyInfo> enemiesReachable;
  110. std::vector<EnemyInfo> enemiesUnreachable;
  111. std::vector<EnemyInfo> enemiesInvincible;
  112. if(stack->creatureId() == CreatureID::CATAPULT)
  113. {
  114. BattleAction attack;
  115. static const std::vector<int> wallHexes = {50, 183, 182, 130, 78, 29, 12, 95};
  116. auto seletectedHex = *RandomGeneratorUtil::nextItem(wallHexes, CRandomGenerator::getDefault());
  117. attack.aimToHex(seletectedHex);
  118. attack.actionType = EActionType::CATAPULT;
  119. attack.side = side;
  120. attack.stackNumber = stack->unitId();
  121. cb->battleMakeUnitAction(battleID, attack);
  122. return;
  123. }
  124. else if(stack->hasBonusOfType(BonusType::SIEGE_WEAPON))
  125. {
  126. cb->battleMakeUnitAction(battleID, BattleAction::makeDefend(stack));
  127. return;
  128. }
  129. for (const CStack *s : cb->getBattle(battleID)->battleGetStacks(CBattleInfoEssentials::ONLY_ENEMY))
  130. {
  131. if (s->isInvincible())
  132. {
  133. enemiesInvincible.push_back(s);
  134. }
  135. else if(cb->getBattle(battleID)->battleCanShoot(stack, s->getPosition()))
  136. {
  137. enemiesShootable.push_back(s);
  138. }
  139. else
  140. {
  141. BattleHexArray avHexes = cb->getBattle(battleID)->battleGetAvailableHexes(stack, false);
  142. for (const BattleHex & hex : avHexes)
  143. {
  144. if(CStack::isMeleeAttackPossible(stack, s, hex))
  145. {
  146. auto i = std::find(enemiesReachable.begin(), enemiesReachable.end(), s);
  147. if(i == enemiesReachable.end())
  148. {
  149. enemiesReachable.push_back(s);
  150. i = enemiesReachable.begin() + (enemiesReachable.size() - 1);
  151. }
  152. i->attackFrom.insert(hex);
  153. }
  154. }
  155. if(!vstd::contains(enemiesReachable, s) && s->getPosition().isValid())
  156. enemiesUnreachable.push_back(s);
  157. }
  158. }
  159. for ( auto & enemy : enemiesReachable )
  160. enemy.calcDmg(cb, battleID, stack);
  161. for ( auto & enemy : enemiesShootable )
  162. enemy.calcDmg(cb, battleID, stack);
  163. if(enemiesShootable.size())
  164. {
  165. const EnemyInfo &ei= *std::max_element(enemiesShootable.begin(), enemiesShootable.end(), isMoreProfitable);
  166. cb->battleMakeUnitAction(battleID, BattleAction::makeShotAttack(stack, ei.s));
  167. return;
  168. }
  169. else if(enemiesReachable.size())
  170. {
  171. const EnemyInfo &ei= *std::max_element(enemiesReachable.begin(), enemiesReachable.end(), &isMoreProfitable);
  172. BattleHex targetHex = *std::max_element(ei.attackFrom.begin(), ei.attackFrom.end(), [&](auto a, auto b) { return willSecondHexBlockMoreEnemyShooters(cb, battleID, a, b);});
  173. cb->battleMakeUnitAction(battleID, BattleAction::makeMeleeAttack(stack, ei.s->getPosition(), targetHex));
  174. return;
  175. }
  176. else if(enemiesUnreachable.size()) //due to #955 - a buggy battle may occur when there are no enemies
  177. {
  178. if(moveStackToClosestEnemy(battleID, stack, dists, enemiesUnreachable))
  179. return;
  180. }
  181. else if(enemiesInvincible.size())
  182. {
  183. if(moveStackToClosestEnemy(battleID, stack, dists, enemiesInvincible))
  184. return;
  185. }
  186. cb->battleMakeUnitAction(battleID, BattleAction::makeDefend(stack));
  187. return;
  188. }
  189. bool CStupidAI::moveStackToClosestEnemy(const BattleID & battleID, const CStack * stack, const ReachabilityInfo & dists, const std::vector<EnemyInfo> &enemyInfos)
  190. {
  191. auto closestEnemy = vstd::minElementByFun(enemyInfos,[&](const EnemyInfo & ei) -> int
  192. {
  193. return dists.distToNearestNeighbour(stack, ei.s);
  194. }
  195. );
  196. if(dists.distToNearestNeighbour(stack, closestEnemy->s) < GameConstants::BFIELD_SIZE)
  197. {
  198. cb->battleMakeUnitAction(battleID, goTowards(battleID, stack, closestEnemy->s->getAttackableHexes(stack)));
  199. return true;
  200. }
  201. return false;
  202. }
  203. void CStupidAI::battleAttack(const BattleID & battleID, const BattleAttack *ba)
  204. {
  205. print("battleAttack called");
  206. }
  207. void CStupidAI::battleStacksAttacked(const BattleID & battleID, const std::vector<BattleStackAttacked> & bsa, bool ranged)
  208. {
  209. print("battleStacksAttacked called");
  210. }
  211. void CStupidAI::battleEnd(const BattleID & battleID, const BattleResult *br, QueryID queryID)
  212. {
  213. print("battleEnd called");
  214. }
  215. // void CStupidAI::battleResultsApplied()
  216. // {
  217. // print("battleResultsApplied called");
  218. // }
  219. void CStupidAI::battleNewRoundFirst(const BattleID & battleID)
  220. {
  221. print("battleNewRoundFirst called");
  222. }
  223. void CStupidAI::battleNewRound(const BattleID & battleID)
  224. {
  225. print("battleNewRound called");
  226. }
  227. void CStupidAI::battleStackMoved(const BattleID & battleID, const CStack * stack, const BattleHexArray & dest, int distance, bool teleport)
  228. {
  229. print("battleStackMoved called");
  230. }
  231. void CStupidAI::battleSpellCast(const BattleID & battleID, const BattleSpellCast *sc)
  232. {
  233. print("battleSpellCast called");
  234. }
  235. void CStupidAI::battleStacksEffectsSet(const BattleID & battleID, const SetStackEffect & sse)
  236. {
  237. print("battleStacksEffectsSet called");
  238. }
  239. void CStupidAI::battleStart(const BattleID & battleID, const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, BattleSide Side, bool replayAllowed)
  240. {
  241. print("battleStart called");
  242. side = Side;
  243. }
  244. void CStupidAI::battleCatapultAttacked(const BattleID & battleID, const CatapultAttack & ca)
  245. {
  246. print("battleCatapultAttacked called");
  247. }
  248. void CStupidAI::print(const std::string &text) const
  249. {
  250. logAi->trace("CStupidAI [%p]: %s", this, text);
  251. }
  252. BattleAction CStupidAI::goTowards(const BattleID & battleID, const CStack * stack, BattleHexArray hexes) const
  253. {
  254. auto reachability = cb->getBattle(battleID)->getReachability(stack);
  255. auto avHexes = cb->getBattle(battleID)->battleGetAvailableHexes(reachability, stack, false);
  256. if(!avHexes.size() || !hexes.size()) //we are blocked or dest is blocked
  257. {
  258. return BattleAction::makeDefend(stack);
  259. }
  260. hexes.sort([&](const BattleHex & h1, const BattleHex & h2) -> bool
  261. {
  262. return reachability.distances[h1.toInt()] < reachability.distances[h2.toInt()];
  263. });
  264. for(const auto & hex : hexes)
  265. {
  266. if(avHexes.contains(hex))
  267. {
  268. if(stack->position == hex)
  269. return BattleAction::makeDefend(stack);
  270. return BattleAction::makeMove(stack, hex);
  271. }
  272. if(stack->coversPos(hex))
  273. {
  274. logAi->warn("Warning: already standing on neighbouring tile!");
  275. //We shouldn't even be here...
  276. return BattleAction::makeDefend(stack);
  277. }
  278. }
  279. BattleHex bestneighbour = hexes.front();
  280. if(reachability.distances[bestneighbour.toInt()] > GameConstants::BFIELD_SIZE)
  281. {
  282. return BattleAction::makeDefend(stack);
  283. }
  284. if(stack->hasBonusOfType(BonusType::FLYING))
  285. {
  286. // Flying stack doesn't go hex by hex, so we can't backtrack using predecessors.
  287. // We just check all available hexes and pick the one closest to the target.
  288. auto nearestAvailableHex = vstd::minElementByFun(avHexes, [&](const BattleHex & hex) -> int
  289. {
  290. return BattleHex::getDistance(bestneighbour, hex);
  291. });
  292. return BattleAction::makeMove(stack, *nearestAvailableHex);
  293. }
  294. else
  295. {
  296. BattleHex currentDest = bestneighbour;
  297. while(1)
  298. {
  299. if(!currentDest.isValid())
  300. {
  301. logAi->error("CBattleAI::goTowards: internal error");
  302. return BattleAction::makeDefend(stack);
  303. }
  304. if(avHexes.contains(currentDest))
  305. {
  306. if(stack->position == currentDest)
  307. return BattleAction::makeDefend(stack);
  308. return BattleAction::makeMove(stack, currentDest);
  309. }
  310. currentDest = reachability.predecessors[currentDest.toInt()];
  311. }
  312. }
  313. }