StupidAI.cpp 8.9 KB

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