StupidAI.cpp 9.5 KB

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