StupidAI.cpp 9.5 KB

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