BattleExchangeVariant.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. /*
  2. * BattleAI.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 "BattleExchangeVariant.h"
  12. #include "../../lib/CStack.h"
  13. int64_t BattleExchangeVariant::trackAttack(const AttackPossibility & ap, HypotheticBattle * state)
  14. {
  15. auto affectedUnits = ap.affectedUnits;
  16. affectedUnits.push_back(ap.attackerState);
  17. for(auto affectedUnit : affectedUnits)
  18. {
  19. auto unitToUpdate = state->getForUpdate(affectedUnit->unitId());
  20. unitToUpdate->health = affectedUnit->health;
  21. unitToUpdate->shots = affectedUnit->shots;
  22. unitToUpdate->counterAttacks = affectedUnit->counterAttacks;
  23. unitToUpdate->movedThisRound = affectedUnit->movedThisRound;
  24. }
  25. auto attackValue = ap.attackValue();
  26. dpsScore += attackValue;
  27. logAi->trace(
  28. "%s -> %s, ap attack, %s, dps: %d, score: %d",
  29. ap.attack.attacker->getDescription(),
  30. ap.attack.defender->getDescription(),
  31. ap.attack.shooting ? "shot" : "mellee",
  32. ap.damageDealt,
  33. attackValue);
  34. return attackValue;
  35. }
  36. int64_t BattleExchangeVariant::trackAttack(
  37. std::shared_ptr<StackWithBonuses> attacker,
  38. std::shared_ptr<StackWithBonuses> defender,
  39. bool shooting,
  40. bool isOurAttack,
  41. std::shared_ptr<CBattleInfoCallback> cb,
  42. bool evaluateOnly)
  43. {
  44. const std::string cachingStringBlocksRetaliation = "type_BLOCKS_RETALIATION";
  45. static const auto selectorBlocksRetaliation = Selector::type()(Bonus::BLOCKS_RETALIATION);
  46. const bool counterAttacksBlocked = attacker->hasBonus(selectorBlocksRetaliation, cachingStringBlocksRetaliation);
  47. TDmgRange retalitation;
  48. BattleAttackInfo bai(attacker.get(), defender.get(), shooting);
  49. auto attack = cb->battleEstimateDamage(bai, &retalitation);
  50. int64_t attackDamage = (attack.first + attack.second) / 2;
  51. int64_t defenderDpsReduce = calculateDpsReduce(attacker.get(), defender.get(), attackDamage, cb);
  52. int64_t attackerDpsReduce = 0;
  53. if(!evaluateOnly)
  54. {
  55. logAi->trace(
  56. "%s -> %s, normal attack, %s, dps: %d, %d",
  57. attacker->getDescription(),
  58. defender->getDescription(),
  59. shooting ? "shot" : "mellee",
  60. attackDamage,
  61. defenderDpsReduce);
  62. if(isOurAttack)
  63. {
  64. dpsScore += defenderDpsReduce;
  65. attackerValue[attacker->unitId()].value += defenderDpsReduce;
  66. }
  67. else
  68. dpsScore -= defenderDpsReduce;
  69. defender->damage(attackDamage);
  70. attacker->afterAttack(shooting, false);
  71. }
  72. if(defender->alive() && defender->ableToRetaliate() && !counterAttacksBlocked && !shooting)
  73. {
  74. if(retalitation.second != 0)
  75. {
  76. auto retalitationDamage = (retalitation.first + retalitation.second) / 2;
  77. attackerDpsReduce = calculateDpsReduce(defender.get(), attacker.get(), retalitationDamage, cb);
  78. if(!evaluateOnly)
  79. {
  80. logAi->trace(
  81. "%s -> %s, retalitation, dps: %d, %d",
  82. defender->getDescription(),
  83. attacker->getDescription(),
  84. retalitationDamage,
  85. attackerDpsReduce);
  86. if(isOurAttack)
  87. {
  88. dpsScore -= attackerDpsReduce;
  89. attackerValue[attacker->unitId()].isRetalitated = true;
  90. }
  91. else
  92. {
  93. dpsScore += attackerDpsReduce;
  94. attackerValue[defender->unitId()].value += attackerDpsReduce;
  95. }
  96. attacker->damage(retalitationDamage);
  97. defender->afterAttack(false, true);
  98. }
  99. }
  100. }
  101. auto score = defenderDpsReduce - attackerDpsReduce;
  102. if(!score)
  103. {
  104. logAi->trace("Zero %d %d", defenderDpsReduce, attackerDpsReduce);
  105. }
  106. return score;
  107. }
  108. int64_t BattleExchangeVariant::calculateDpsReduce(
  109. const battle::Unit * attacker,
  110. const battle::Unit * defender,
  111. uint64_t damageDealt,
  112. std::shared_ptr<CBattleInfoCallback> cb) const
  113. {
  114. vstd::amin(damageDealt, defender->getAvailableHealth());
  115. auto enemyDamageBeforeAttack = cb->battleEstimateDamage(BattleAttackInfo(defender, attacker, defender->canShoot()));
  116. auto enemiesKilled = damageDealt / defender->MaxHealth() + (damageDealt % defender->MaxHealth() >= defender->getFirstHPleft() ? 1 : 0);
  117. auto enemyDps = (enemyDamageBeforeAttack.first + enemyDamageBeforeAttack.second) / 2;
  118. return (int64_t)(enemyDps * enemiesKilled / (double)defender->getCount()
  119. + enemyDps / (double)defender->getCount() * ((damageDealt - defender->getFirstHPleft()) % defender->MaxHealth()) / defender->MaxHealth());
  120. };
  121. EvaluationResult BattleExchangeEvaluator::findBestTarget(const battle::Unit * activeStack, PotentialTargets & targets, HypotheticBattle & hb)
  122. {
  123. EvaluationResult result(targets.bestAction());
  124. updateReachabilityMap(hb);
  125. for(auto & ap : targets.possibleAttacks)
  126. {
  127. int64_t score = calculateExchange(ap);
  128. if(score > result.score)
  129. {
  130. result.score = score;
  131. result.bestAttack = ap;
  132. }
  133. }
  134. if(!activeStack->waited())
  135. {
  136. logAi->trace("Evaluating waited attack for %s", activeStack->getDescription());
  137. hb.getForUpdate(activeStack->unitId())->waiting = true;
  138. hb.getForUpdate(activeStack->unitId())->waitedThisTurn = true;
  139. updateReachabilityMap(hb);
  140. for(auto & ap : targets.possibleAttacks)
  141. {
  142. int64_t score = calculateExchange(ap);
  143. if(score > result.score)
  144. {
  145. result.score = score;
  146. result.bestAttack = ap;
  147. result.wait = true;
  148. }
  149. }
  150. }
  151. return result;
  152. }
  153. std::vector<const battle::Unit *> BattleExchangeEvaluator::getExchangeUnits(
  154. const AttackPossibility & ap)
  155. {
  156. auto hexes = ap.attack.defender->getHexes();
  157. if(!ap.attack.shooting) hexes.push_back(ap.from);
  158. std::vector<const battle::Unit *> exchangeUnits;
  159. std::vector<const battle::Unit *> allReachableUnits;
  160. for(auto hex : hexes)
  161. {
  162. vstd::concatenate(allReachableUnits, reachabilityMap[hex]);
  163. }
  164. vstd::removeDuplicates(allReachableUnits);
  165. if(allReachableUnits.size() < 2)
  166. {
  167. logAi->trace("Reachability map contains only %d stacks", allReachableUnits.size());
  168. return exchangeUnits;
  169. }
  170. for(int turn = 0; turn < turnOrder.size(); turn++)
  171. {
  172. for(auto unit : turnOrder[turn])
  173. {
  174. if(vstd::contains(allReachableUnits, unit))
  175. exchangeUnits.push_back(unit);
  176. }
  177. }
  178. return exchangeUnits;
  179. }
  180. int64_t BattleExchangeEvaluator::calculateExchange(const AttackPossibility & ap)
  181. {
  182. logAi->trace("Battle exchange at %d", ap.attack.shooting ? ap.dest : ap.from);
  183. std::vector<const battle::Unit *> ourStacks;
  184. std::vector<const battle::Unit *> enemyStacks;
  185. enemyStacks.push_back(ap.attack.defender);
  186. std::vector<const battle::Unit *> exchangeUnits = getExchangeUnits(ap);
  187. if(exchangeUnits.empty())
  188. {
  189. return 0;
  190. }
  191. HypotheticBattle exchangeBattle(env.get(), cb);
  192. BattleExchangeVariant v;
  193. auto melleeAttackers = ourStacks;
  194. vstd::removeDuplicates(melleeAttackers);
  195. vstd::erase_if(melleeAttackers, [&](const battle::Unit * u) -> bool
  196. {
  197. return !cb->battleCanShoot(u);
  198. });
  199. for(auto unit : exchangeUnits)
  200. {
  201. bool isOur = cb->battleMatchOwner(ap.attack.attacker, unit, true);
  202. auto & attackerQueue = isOur ? ourStacks : enemyStacks;
  203. auto & oppositeQueue = isOur ? enemyStacks : ourStacks;
  204. if(!vstd::contains(attackerQueue, unit))
  205. {
  206. attackerQueue.push_back(unit);
  207. }
  208. }
  209. bool canUseAp = true;
  210. for(auto activeUnit : exchangeUnits)
  211. {
  212. bool isOur = cb->battleMatchOwner(ap.attack.attacker, activeUnit, true);
  213. battle::Units & attackerQueue = isOur ? ourStacks : enemyStacks;
  214. battle::Units & oppositeQueue = isOur ? enemyStacks : ourStacks;
  215. auto attacker = exchangeBattle.getForUpdate(activeUnit->unitId());
  216. if(!attacker->alive() || oppositeQueue.empty())
  217. {
  218. logAi->trace(
  219. "Attacker [%s] dead(%d) or opposite queue empty(%d)",
  220. attacker->getDescription(),
  221. attacker->alive() ? 0 : 1,
  222. oppositeQueue.size());
  223. continue;
  224. }
  225. auto targetUnit = ap.attack.defender;
  226. if(!isOur || !exchangeBattle.getForUpdate(targetUnit->unitId())->alive())
  227. {
  228. targetUnit = *vstd::maxElementByFun(oppositeQueue, [&](const battle::Unit * u) -> int64_t
  229. {
  230. auto stackWithBonuses = exchangeBattle.getForUpdate(u->unitId());
  231. auto score = v.trackAttack(
  232. attacker,
  233. stackWithBonuses,
  234. exchangeBattle.battleCanShoot(stackWithBonuses.get()),
  235. isOur,
  236. cb,
  237. true);
  238. logAi->trace("Best target selector %s->%s score = %d", attacker->getDescription(), u->getDescription(), score);
  239. return score;
  240. });
  241. }
  242. auto defender = exchangeBattle.getForUpdate(targetUnit->unitId());
  243. auto shooting = cb->battleCanShoot(attacker.get());
  244. const int totalAttacks = attacker->getTotalAttacks(shooting);
  245. if(canUseAp && activeUnit == ap.attack.attacker && targetUnit == ap.attack.defender)
  246. {
  247. v.trackAttack(ap, &exchangeBattle);
  248. }
  249. else
  250. {
  251. for(int i = 0; i < totalAttacks; i++)
  252. {
  253. v.trackAttack(attacker, defender, shooting, isOur, cb);
  254. if(!attacker->alive() || !defender->alive())
  255. break;
  256. }
  257. }
  258. canUseAp = false;
  259. vstd::erase_if(attackerQueue, [&](const battle::Unit * u) -> bool
  260. {
  261. return !exchangeBattle.getForUpdate(u->unitId())->alive();
  262. });
  263. vstd::erase_if(oppositeQueue, [&](const battle::Unit * u) -> bool
  264. {
  265. return !exchangeBattle.getForUpdate(u->unitId())->alive();
  266. });
  267. }
  268. v.adjustPositions(melleeAttackers, ap, reachabilityMap);
  269. logAi->trace("Exchange score: %ld", v.getScore());
  270. return v.getScore();
  271. }
  272. void BattleExchangeVariant::adjustPositions(
  273. std::vector<const battle::Unit*> attackers,
  274. const AttackPossibility & ap,
  275. std::map<BattleHex, battle::Units> & reachabilityMap)
  276. {
  277. auto hexes = ap.attack.defender->getSurroundingHexes();
  278. boost::sort(attackers, [&](const battle::Unit * u1, const battle::Unit * u2) -> bool
  279. {
  280. if(attackerValue[u1->unitId()].isRetalitated && !attackerValue[u2->unitId()].isRetalitated)
  281. return true;
  282. if(attackerValue[u2->unitId()].isRetalitated && !attackerValue[u1->unitId()].isRetalitated)
  283. return false;
  284. return attackerValue[u1->unitId()].value > attackerValue[u2->unitId()].value;
  285. });
  286. if(!ap.attack.shooting)
  287. {
  288. vstd::erase_if_present(hexes, ap.from);
  289. vstd::erase_if_present(hexes, ap.attack.attacker->occupiedHex(ap.attack.attackerPos));
  290. }
  291. int64_t notRealizedDps = 0;
  292. for(auto unit : attackers)
  293. {
  294. if(unit->unitId() == ap.attack.attacker->unitId())
  295. continue;
  296. if(!vstd::contains_if(hexes, [&](BattleHex h) -> bool
  297. {
  298. return vstd::contains(reachabilityMap[h], unit);
  299. }))
  300. {
  301. notRealizedDps += attackerValue[unit->unitId()].value;
  302. continue;
  303. }
  304. auto desiredPosition = vstd::minElementByFun(hexes, [&](BattleHex h) -> int64_t
  305. {
  306. auto score = vstd::contains(reachabilityMap[h], unit)
  307. ? reachabilityMap[h].size()
  308. : 1000;
  309. if(unit->doubleWide())
  310. {
  311. auto backHex = unit->occupiedHex(h);
  312. if(vstd::contains(hexes, backHex))
  313. score += reachabilityMap[backHex].size();
  314. }
  315. return score;
  316. });
  317. hexes.erase(desiredPosition);
  318. }
  319. if(notRealizedDps > ap.attackValue() && notRealizedDps > attackerValue[ap.attack.attacker->unitId()].value)
  320. {
  321. dpsScore = EvaluationResult::INEFFECTIVE_SCORE;
  322. }
  323. }
  324. void BattleExchangeEvaluator::updateReachabilityMap(HypotheticBattle & hb)
  325. {
  326. turnOrder.clear();
  327. hb.battleGetTurnOrder(turnOrder, 1000, 2);
  328. reachabilityMap.clear();
  329. for(int turn = 0; turn < turnOrder.size(); turn++)
  330. {
  331. auto & turnQueue = turnOrder[turn];
  332. HypotheticBattle turnBattle(env.get(), cb);
  333. for(const battle::Unit * unit : turnQueue)
  334. {
  335. auto unitReachability = turnBattle.getReachability(unit);
  336. for(BattleHex hex = BattleHex::TOP_LEFT; hex.isValid(); hex = hex + 1)
  337. {
  338. bool reachable = unitReachability.distances[hex] <= unit->Speed(turn);
  339. if(!reachable && unitReachability.accessibility[hex] == EAccessibility::ALIVE_STACK)
  340. {
  341. const battle::Unit * hexStack = cb->battleGetUnitByPos(hex);
  342. if(hexStack && cb->battleMatchOwner(unit, hexStack, false))
  343. {
  344. for(BattleHex neighbor : hex.neighbouringTiles())
  345. {
  346. reachable = unitReachability.distances[neighbor] <= unit->Speed(turn);
  347. if(reachable) break;
  348. }
  349. }
  350. }
  351. if(reachable)
  352. {
  353. reachabilityMap[hex].push_back(unit);
  354. }
  355. }
  356. }
  357. }
  358. }
  359. bool BattleExchangeEvaluator::checkPositionBlocksOurStacks(HypotheticBattle & hb, const battle::Unit * activeUnit, BattleHex position)
  360. {
  361. int blockingScore = 0;
  362. for(int turn = 0; turn < turnOrder.size(); turn++)
  363. {
  364. auto & turnQueue = turnOrder[turn];
  365. HypotheticBattle turnBattle(env.get(), cb);
  366. auto unitToUpdate = turnBattle.getForUpdate(activeUnit->unitId());
  367. unitToUpdate->setPosition(position);
  368. for(const battle::Unit * unit : turnQueue)
  369. {
  370. if(unit->unitId() == unitToUpdate->unitId() || cb->battleMatchOwner(unit, activeUnit, false))
  371. continue;
  372. auto unitReachability = turnBattle.getReachability(unit);
  373. for(BattleHex hex = BattleHex::TOP_LEFT; hex.isValid(); hex = hex + 1)
  374. {
  375. bool enemyUnit = false;
  376. bool reachable = unitReachability.distances[hex] <= unit->Speed(turn);
  377. if(!reachable && unitReachability.accessibility[hex] == EAccessibility::ALIVE_STACK)
  378. {
  379. const battle::Unit * hexStack = turnBattle.battleGetUnitByPos(hex);
  380. if(hexStack && cb->battleMatchOwner(unit, hexStack, false))
  381. {
  382. enemyUnit = true;
  383. for(BattleHex neighbor : hex.neighbouringTiles())
  384. {
  385. reachable = unitReachability.distances[neighbor] <= unit->Speed(turn);
  386. if(reachable) break;
  387. }
  388. }
  389. }
  390. if(!reachable && vstd::contains(reachabilityMap[hex], unit))
  391. {
  392. blockingScore += enemyUnit ? 100 : 1;
  393. }
  394. }
  395. }
  396. }
  397. logAi->trace("Position %d, blocking score %d", position.hex, blockingScore);
  398. return blockingScore > 50;
  399. }