BattleExchangeVariant.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864
  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. AttackerValue::AttackerValue()
  14. {
  15. value = 0;
  16. isRetalitated = false;
  17. }
  18. MoveTarget::MoveTarget()
  19. : positions(), cachedAttack(), score(EvaluationResult::INEFFECTIVE_SCORE), scorePerTurn(EvaluationResult::INEFFECTIVE_SCORE)
  20. {
  21. turnsToRich = 1;
  22. }
  23. float BattleExchangeVariant::trackAttack(
  24. const AttackPossibility & ap,
  25. std::shared_ptr<HypotheticBattle> hb,
  26. DamageCache & damageCache)
  27. {
  28. auto attacker = hb->getForUpdate(ap.attack.attacker->unitId());
  29. const std::string cachingStringBlocksRetaliation = "type_BLOCKS_RETALIATION";
  30. static const auto selectorBlocksRetaliation = Selector::type()(BonusType::BLOCKS_RETALIATION);
  31. const bool counterAttacksBlocked = attacker->hasBonus(selectorBlocksRetaliation, cachingStringBlocksRetaliation);
  32. float attackValue = 0;
  33. auto affectedUnits = ap.affectedUnits;
  34. affectedUnits.push_back(ap.attackerState);
  35. for(auto affectedUnit : affectedUnits)
  36. {
  37. auto unitToUpdate = hb->getForUpdate(affectedUnit->unitId());
  38. if(unitToUpdate->unitSide() == attacker->unitSide())
  39. {
  40. if(unitToUpdate->unitId() == attacker->unitId())
  41. {
  42. auto defender = hb->getForUpdate(ap.attack.defender->unitId());
  43. if(!defender->alive() || counterAttacksBlocked || ap.attack.shooting || !defender->ableToRetaliate())
  44. continue;
  45. auto retaliationDamage = damageCache.getDamage(defender.get(), unitToUpdate.get(), hb);
  46. auto attackerDamageReduce = AttackPossibility::calculateDamageReduce(defender.get(), unitToUpdate.get(), retaliationDamage, damageCache, hb);
  47. attackValue -= attackerDamageReduce;
  48. dpsScore.ourDamageReduce += attackerDamageReduce;
  49. attackerValue[unitToUpdate->unitId()].isRetalitated = true;
  50. unitToUpdate->damage(retaliationDamage);
  51. defender->afterAttack(false, true);
  52. #if BATTLE_TRACE_LEVEL>=1
  53. logAi->trace(
  54. "%s -> %s, ap retalitation, %s, dps: %2f, score: %2f",
  55. defender->getDescription(),
  56. unitToUpdate->getDescription(),
  57. ap.attack.shooting ? "shot" : "mellee",
  58. retaliationDamage,
  59. attackerDamageReduce);
  60. #endif
  61. }
  62. else
  63. {
  64. auto collateralDamage = damageCache.getDamage(attacker.get(), unitToUpdate.get(), hb);
  65. auto collateralDamageReduce = AttackPossibility::calculateDamageReduce(attacker.get(), unitToUpdate.get(), collateralDamage, damageCache, hb);
  66. attackValue -= collateralDamageReduce;
  67. dpsScore.ourDamageReduce += collateralDamageReduce;
  68. unitToUpdate->damage(collateralDamage);
  69. #if BATTLE_TRACE_LEVEL>=1
  70. logAi->trace(
  71. "%s -> %s, ap collateral, %s, dps: %2f, score: %2f",
  72. attacker->getDescription(),
  73. unitToUpdate->getDescription(),
  74. ap.attack.shooting ? "shot" : "mellee",
  75. collateralDamage,
  76. collateralDamageReduce);
  77. #endif
  78. }
  79. }
  80. else
  81. {
  82. int64_t attackDamage = damageCache.getDamage(attacker.get(), unitToUpdate.get(), hb);
  83. float defenderDamageReduce = AttackPossibility::calculateDamageReduce(attacker.get(), unitToUpdate.get(), attackDamage, damageCache, hb);
  84. attackValue += defenderDamageReduce;
  85. dpsScore.enemyDamageReduce += defenderDamageReduce;
  86. attackerValue[attacker->unitId()].value += defenderDamageReduce;
  87. unitToUpdate->damage(attackDamage);
  88. #if BATTLE_TRACE_LEVEL>=1
  89. logAi->trace(
  90. "%s -> %s, ap attack, %s, dps: %2f, score: %2f",
  91. attacker->getDescription(),
  92. unitToUpdate->getDescription(),
  93. ap.attack.shooting ? "shot" : "mellee",
  94. attackDamage,
  95. defenderDamageReduce);
  96. #endif
  97. }
  98. }
  99. attackValue += ap.shootersBlockedDmg;
  100. dpsScore.enemyDamageReduce += ap.shootersBlockedDmg;
  101. attacker->afterAttack(ap.attack.shooting, false);
  102. return attackValue;
  103. }
  104. float BattleExchangeVariant::trackAttack(
  105. std::shared_ptr<StackWithBonuses> attacker,
  106. std::shared_ptr<StackWithBonuses> defender,
  107. bool shooting,
  108. bool isOurAttack,
  109. DamageCache & damageCache,
  110. std::shared_ptr<HypotheticBattle> hb,
  111. bool evaluateOnly)
  112. {
  113. const std::string cachingStringBlocksRetaliation = "type_BLOCKS_RETALIATION";
  114. static const auto selectorBlocksRetaliation = Selector::type()(BonusType::BLOCKS_RETALIATION);
  115. const bool counterAttacksBlocked = attacker->hasBonus(selectorBlocksRetaliation, cachingStringBlocksRetaliation);
  116. int64_t attackDamage = damageCache.getDamage(attacker.get(), defender.get(), hb);
  117. float defenderDamageReduce = AttackPossibility::calculateDamageReduce(attacker.get(), defender.get(), attackDamage, damageCache, hb);
  118. float attackerDamageReduce = 0;
  119. if(!evaluateOnly)
  120. {
  121. #if BATTLE_TRACE_LEVEL>=1
  122. logAi->trace(
  123. "%s -> %s, normal attack, %s, dps: %lld, %2f",
  124. attacker->getDescription(),
  125. defender->getDescription(),
  126. shooting ? "shot" : "mellee",
  127. attackDamage,
  128. defenderDamageReduce);
  129. #endif
  130. if(isOurAttack)
  131. {
  132. dpsScore.enemyDamageReduce += defenderDamageReduce;
  133. attackerValue[attacker->unitId()].value += defenderDamageReduce;
  134. }
  135. else
  136. dpsScore.ourDamageReduce += defenderDamageReduce;
  137. defender->damage(attackDamage);
  138. attacker->afterAttack(shooting, false);
  139. }
  140. if(!evaluateOnly && defender->alive() && defender->ableToRetaliate() && !counterAttacksBlocked && !shooting)
  141. {
  142. auto retaliationDamage = damageCache.getDamage(defender.get(), attacker.get(), hb);
  143. attackerDamageReduce = AttackPossibility::calculateDamageReduce(defender.get(), attacker.get(), retaliationDamage, damageCache, hb);
  144. #if BATTLE_TRACE_LEVEL>=1
  145. logAi->trace(
  146. "%s -> %s, retaliation, dps: %lld, %2f",
  147. defender->getDescription(),
  148. attacker->getDescription(),
  149. retaliationDamage,
  150. attackerDamageReduce);
  151. #endif
  152. if(isOurAttack)
  153. {
  154. dpsScore.ourDamageReduce += attackerDamageReduce;
  155. attackerValue[attacker->unitId()].isRetalitated = true;
  156. }
  157. else
  158. {
  159. dpsScore.enemyDamageReduce += attackerDamageReduce;
  160. attackerValue[defender->unitId()].value += attackerDamageReduce;
  161. }
  162. attacker->damage(retaliationDamage);
  163. defender->afterAttack(false, true);
  164. }
  165. auto score = defenderDamageReduce - attackerDamageReduce;
  166. #if BATTLE_TRACE_LEVEL>=1
  167. if(!score)
  168. {
  169. logAi->trace("Attack has zero score def:%2f att:%2f", defenderDamageReduce, attackerDamageReduce);
  170. }
  171. #endif
  172. return score;
  173. }
  174. float BattleExchangeEvaluator::scoreValue(const BattleScore & score) const
  175. {
  176. return score.enemyDamageReduce * getPositiveEffectMultiplier() - score.ourDamageReduce * getNegativeEffectMultiplier();
  177. }
  178. EvaluationResult BattleExchangeEvaluator::findBestTarget(
  179. const battle::Unit * activeStack,
  180. PotentialTargets & targets,
  181. DamageCache & damageCache,
  182. std::shared_ptr<HypotheticBattle> hb)
  183. {
  184. EvaluationResult result(targets.bestAction());
  185. if(!activeStack->waited() && !activeStack->acquireState()->hadMorale)
  186. {
  187. #if BATTLE_TRACE_LEVEL>=1
  188. logAi->trace("Evaluating waited attack for %s", activeStack->getDescription());
  189. #endif
  190. auto hbWaited = std::make_shared<HypotheticBattle>(env.get(), hb);
  191. hbWaited->getForUpdate(activeStack->unitId())->waiting = true;
  192. hbWaited->getForUpdate(activeStack->unitId())->waitedThisTurn = true;
  193. updateReachabilityMap(hbWaited);
  194. for(auto & ap : targets.possibleAttacks)
  195. {
  196. float score = evaluateExchange(ap, targets, damageCache, hbWaited);
  197. if(score > result.score)
  198. {
  199. result.score = score;
  200. result.bestAttack = ap;
  201. result.wait = true;
  202. }
  203. }
  204. }
  205. #if BATTLE_TRACE_LEVEL>=1
  206. logAi->trace("Evaluating normal attack for %s", activeStack->getDescription());
  207. #endif
  208. updateReachabilityMap(hb);
  209. if(result.bestAttack.attack.shooting && hb->battleHasShootingPenalty(activeStack, result.bestAttack.dest))
  210. {
  211. if(!canBeHitThisTurn(result.bestAttack))
  212. return result; // lets wait
  213. }
  214. for(auto & ap : targets.possibleAttacks)
  215. {
  216. float score = evaluateExchange(ap, targets, damageCache, hb);
  217. if(score >= result.score)
  218. {
  219. result.score = score;
  220. result.bestAttack = ap;
  221. result.wait = false;
  222. }
  223. }
  224. return result;
  225. }
  226. MoveTarget BattleExchangeEvaluator::findMoveTowardsUnreachable(
  227. const battle::Unit * activeStack,
  228. PotentialTargets & targets,
  229. DamageCache & damageCache,
  230. std::shared_ptr<HypotheticBattle> hb)
  231. {
  232. MoveTarget result;
  233. BattleExchangeVariant ev;
  234. if(targets.unreachableEnemies.empty())
  235. return result;
  236. auto speed = activeStack->speed();
  237. if(speed == 0)
  238. return result;
  239. updateReachabilityMap(hb);
  240. auto dists = cb->getReachability(activeStack);
  241. for(const battle::Unit * enemy : targets.unreachableEnemies)
  242. {
  243. std::vector<const battle::Unit *> adjacentStacks = getAdjacentUnits(enemy);
  244. auto closestStack = *vstd::minElementByFun(adjacentStacks, [&](const battle::Unit * u) -> int64_t
  245. {
  246. return dists.distToNearestNeighbour(activeStack, u) * 100000 - activeStack->getTotalHealth();
  247. });
  248. auto distance = dists.distToNearestNeighbour(activeStack, closestStack);
  249. if(distance >= GameConstants::BFIELD_SIZE)
  250. continue;
  251. if(distance <= speed)
  252. continue;
  253. auto turnsToRich = (distance - 1) / speed + 1;
  254. auto hexes = closestStack->getSurroundingHexes();
  255. auto enemySpeed = closestStack->speed();
  256. auto speedRatio = speed / static_cast<float>(enemySpeed);
  257. auto penalty = speedRatio > 1 ? 1 : speedRatio;
  258. for(auto hex : hexes)
  259. {
  260. // FIXME: provide distance info for Jousting bonus
  261. auto bai = BattleAttackInfo(activeStack, closestStack, 0, cb->battleCanShoot(activeStack));
  262. auto attack = AttackPossibility::evaluate(bai, hex, damageCache, hb);
  263. attack.shootersBlockedDmg = 0; // we do not want to count on it, it is not for sure
  264. auto score = calculateExchange(attack, turnsToRich, targets, damageCache, hb);
  265. auto scorePerTurn = BattleScore(score.enemyDamageReduce * std::sqrt(penalty / turnsToRich), score.ourDamageReduce);
  266. if(result.scorePerTurn < scoreValue(scorePerTurn))
  267. {
  268. result.scorePerTurn = scoreValue(scorePerTurn);
  269. result.score = scoreValue(score);
  270. result.positions = closestStack->getAttackableHexes(activeStack);
  271. result.cachedAttack = attack;
  272. result.turnsToRich = turnsToRich;
  273. }
  274. }
  275. }
  276. return result;
  277. }
  278. std::vector<const battle::Unit *> BattleExchangeEvaluator::getAdjacentUnits(const battle::Unit * blockerUnit)
  279. {
  280. std::queue<const battle::Unit *> queue;
  281. std::vector<const battle::Unit *> checkedStacks;
  282. queue.push(blockerUnit);
  283. while(!queue.empty())
  284. {
  285. auto stack = queue.front();
  286. queue.pop();
  287. checkedStacks.push_back(stack);
  288. auto hexes = stack->getSurroundingHexes();
  289. for(auto hex : hexes)
  290. {
  291. auto neighbor = cb->battleGetUnitByPos(hex);
  292. if(neighbor && neighbor->unitSide() == stack->unitSide() && !vstd::contains(checkedStacks, neighbor))
  293. {
  294. queue.push(neighbor);
  295. checkedStacks.push_back(neighbor);
  296. }
  297. }
  298. }
  299. return checkedStacks;
  300. }
  301. ReachabilityData BattleExchangeEvaluator::getExchangeUnits(
  302. const AttackPossibility & ap,
  303. PotentialTargets & targets,
  304. std::shared_ptr<HypotheticBattle> hb)
  305. {
  306. ReachabilityData result;
  307. auto hexes = ap.attack.defender->getHexes();
  308. if(!ap.attack.shooting) hexes.push_back(ap.from);
  309. std::vector<const battle::Unit *> allReachableUnits;
  310. for(auto hex : hexes)
  311. {
  312. vstd::concatenate(allReachableUnits, reachabilityMap[hex]);
  313. }
  314. vstd::removeDuplicates(allReachableUnits);
  315. auto copy = allReachableUnits;
  316. for(auto unit : copy)
  317. {
  318. for(auto adjacentUnit : getAdjacentUnits(unit))
  319. {
  320. auto unitWithBonuses = hb->battleGetUnitByID(adjacentUnit->unitId());
  321. if(vstd::contains(targets.unreachableEnemies, adjacentUnit)
  322. && !vstd::contains(allReachableUnits, unitWithBonuses))
  323. {
  324. allReachableUnits.push_back(unitWithBonuses);
  325. }
  326. }
  327. }
  328. vstd::removeDuplicates(allReachableUnits);
  329. if(!vstd::contains(allReachableUnits, ap.attack.attacker))
  330. {
  331. allReachableUnits.push_back(ap.attack.attacker);
  332. }
  333. if(allReachableUnits.size() < 2)
  334. {
  335. #if BATTLE_TRACE_LEVEL>=1
  336. logAi->trace("Reachability map contains only %d stacks", allReachableUnits.size());
  337. #endif
  338. return result;
  339. }
  340. for(auto unit : allReachableUnits)
  341. {
  342. auto accessible = !unit->canShoot();
  343. if(!accessible)
  344. {
  345. for(auto hex : unit->getSurroundingHexes())
  346. {
  347. if(ap.attack.defender->coversPos(hex))
  348. {
  349. accessible = true;
  350. }
  351. }
  352. }
  353. if(accessible)
  354. result.melleeAccessible.push_back(unit);
  355. else
  356. result.shooters.push_back(unit);
  357. }
  358. for(int turn = 0; turn < turnOrder.size(); turn++)
  359. {
  360. for(auto unit : turnOrder[turn])
  361. {
  362. if(vstd::contains(allReachableUnits, unit))
  363. result.units.push_back(unit);
  364. }
  365. }
  366. vstd::erase_if(result.units, [&](const battle::Unit * u) -> bool
  367. {
  368. return !hb->battleGetUnitByID(u->unitId())->alive();
  369. });
  370. return result;
  371. }
  372. float BattleExchangeEvaluator::evaluateExchange(
  373. const AttackPossibility & ap,
  374. PotentialTargets & targets,
  375. DamageCache & damageCache,
  376. std::shared_ptr<HypotheticBattle> hb)
  377. {
  378. BattleScore score = calculateExchange(ap, targets, damageCache, hb);
  379. return scoreValue(score);
  380. }
  381. BattleScore BattleExchangeEvaluator::calculateExchange(
  382. const AttackPossibility & ap,
  383. PotentialTargets & targets,
  384. DamageCache & damageCache,
  385. std::shared_ptr<HypotheticBattle> hb)
  386. {
  387. #if BATTLE_TRACE_LEVEL>=1
  388. logAi->trace("Battle exchange at %d", ap.attack.shooting ? ap.dest.hex : ap.from.hex);
  389. #endif
  390. if(cb->battleGetMySide() == BattlePerspective::LEFT_SIDE
  391. && cb->battleGetGateState() == EGateState::BLOCKED
  392. && ap.attack.defender->coversPos(BattleHex::GATE_BRIDGE))
  393. {
  394. return BattleScore(EvaluationResult::INEFFECTIVE_SCORE, 0);
  395. }
  396. std::vector<const battle::Unit *> ourStacks;
  397. std::vector<const battle::Unit *> enemyStacks;
  398. if(hb->battleGetUnitByID(ap.attack.defender->unitId())->alive())
  399. enemyStacks.push_back(ap.attack.defender);
  400. vstd::amin(turn, reachabilityMapByTurns.size() - 1);
  401. ReachabilityData exchangeUnits = getExchangeUnits(ap, turn, targets, hb);
  402. if(exchangeUnits.units.empty())
  403. {
  404. return BattleScore();
  405. }
  406. auto exchangeBattle = std::make_shared<HypotheticBattle>(env.get(), hb);
  407. BattleExchangeVariant v;
  408. for(auto unit : exchangeUnits.units)
  409. {
  410. if(unit->isTurret())
  411. continue;
  412. bool isOur = exchangeBattle->battleMatchOwner(ap.attack.attacker, unit, true);
  413. auto & attackerQueue = isOur ? ourStacks : enemyStacks;
  414. if(exchangeBattle->getForUpdate(unit->unitId())->alive() && !vstd::contains(attackerQueue, unit))
  415. {
  416. attackerQueue.push_back(unit);
  417. }
  418. }
  419. auto melleeAttackers = ourStacks;
  420. vstd::removeDuplicates(melleeAttackers);
  421. vstd::erase_if(melleeAttackers, [&](const battle::Unit * u) -> bool
  422. {
  423. return !cb->battleCanShoot(u);
  424. });
  425. bool canUseAp = true;
  426. for(auto activeUnit : exchangeUnits.units)
  427. {
  428. bool isOur = exchangeBattle->battleMatchOwner(ap.attack.attacker, activeUnit, true);
  429. battle::Units & attackerQueue = isOur ? ourStacks : enemyStacks;
  430. battle::Units & oppositeQueue = isOur ? enemyStacks : ourStacks;
  431. auto attacker = exchangeBattle->getForUpdate(activeUnit->unitId());
  432. if(!attacker->alive())
  433. {
  434. #if BATTLE_TRACE_LEVEL>=1
  435. logAi->trace( "Attacker is dead");
  436. #endif
  437. continue;
  438. }
  439. auto targetUnit = ap.attack.defender;
  440. if(!isOur || !exchangeBattle->battleGetUnitByID(targetUnit->unitId())->alive())
  441. {
  442. auto estimateAttack = [&](const battle::Unit * u) -> float
  443. {
  444. auto stackWithBonuses = exchangeBattle->getForUpdate(u->unitId());
  445. auto score = v.trackAttack(
  446. attacker,
  447. stackWithBonuses,
  448. exchangeBattle->battleCanShoot(stackWithBonuses.get()),
  449. isOur,
  450. damageCache,
  451. hb,
  452. true);
  453. #if BATTLE_TRACE_LEVEL>=1
  454. logAi->trace("Best target selector %s->%s score = %2f", attacker->getDescription(), u->getDescription(), score);
  455. #endif
  456. return score;
  457. };
  458. auto unitsInOppositeQueueExceptInaccessible = oppositeQueue;
  459. vstd::erase_if(unitsInOppositeQueueExceptInaccessible, [&](const battle::Unit * u)->bool
  460. {
  461. return vstd::contains(exchangeUnits.shooters, u);
  462. });
  463. if(!unitsInOppositeQueueExceptInaccessible.empty())
  464. {
  465. targetUnit = *vstd::maxElementByFun(unitsInOppositeQueueExceptInaccessible, estimateAttack);
  466. }
  467. else
  468. {
  469. auto reachable = exchangeBattle->battleGetUnitsIf([&](const battle::Unit * u) -> bool
  470. {
  471. if(u->unitSide() == attacker->unitSide())
  472. return false;
  473. if(!exchangeBattle->getForUpdate(u->unitId())->alive())
  474. return false;
  475. return vstd::contains_if(reachabilityMap[u->getPosition()], [&](const battle::Unit * other) -> bool
  476. {
  477. return attacker->unitId() == other->unitId();
  478. });
  479. });
  480. if(!reachable.empty())
  481. {
  482. targetUnit = *vstd::maxElementByFun(reachable, estimateAttack);
  483. }
  484. else
  485. {
  486. #if BATTLE_TRACE_LEVEL>=1
  487. logAi->trace("Battle queue is empty and no reachable enemy.");
  488. #endif
  489. continue;
  490. }
  491. }
  492. }
  493. auto defender = exchangeBattle->getForUpdate(targetUnit->unitId());
  494. auto shooting = exchangeBattle->battleCanShoot(attacker.get());
  495. const int totalAttacks = attacker->getTotalAttacks(shooting);
  496. if(canUseAp && activeUnit->unitId() == ap.attack.attacker->unitId()
  497. && targetUnit->unitId() == ap.attack.defender->unitId())
  498. {
  499. v.trackAttack(ap, exchangeBattle, damageCache);
  500. }
  501. else
  502. {
  503. for(int i = 0; i < totalAttacks; i++)
  504. {
  505. v.trackAttack(attacker, defender, shooting, isOur, damageCache, exchangeBattle);
  506. if(!attacker->alive() || !defender->alive())
  507. break;
  508. }
  509. }
  510. canUseAp = false;
  511. vstd::erase_if(attackerQueue, [&](const battle::Unit * u) -> bool
  512. {
  513. return !exchangeBattle->battleGetUnitByID(u->unitId())->alive();
  514. });
  515. vstd::erase_if(oppositeQueue, [&](const battle::Unit * u) -> bool
  516. {
  517. return !exchangeBattle->battleGetUnitByID(u->unitId())->alive();
  518. });
  519. }
  520. // avoid blocking path for stronger stack by weaker stack
  521. // the method checks if all stacks can be placed around enemy
  522. v.adjustPositions(melleeAttackers, ap, reachabilityMap);
  523. #if BATTLE_TRACE_LEVEL>=1
  524. logAi->trace("Exchange score: enemy: %2f, our -%2f", v.getScore().enemyDamageReduce, v.getScore().ourDamageReduce);
  525. #endif
  526. return v.getScore();
  527. }
  528. void BattleExchangeVariant::adjustPositions(
  529. std::vector<const battle::Unit*> attackers,
  530. const AttackPossibility & ap,
  531. std::map<BattleHex, battle::Units> & reachabilityMap)
  532. {
  533. auto hexes = ap.attack.defender->getSurroundingHexes();
  534. boost::sort(attackers, [&](const battle::Unit * u1, const battle::Unit * u2) -> bool
  535. {
  536. if(attackerValue[u1->unitId()].isRetalitated && !attackerValue[u2->unitId()].isRetalitated)
  537. return true;
  538. if(attackerValue[u2->unitId()].isRetalitated && !attackerValue[u1->unitId()].isRetalitated)
  539. return false;
  540. return attackerValue[u1->unitId()].value > attackerValue[u2->unitId()].value;
  541. });
  542. if(!ap.attack.shooting)
  543. {
  544. vstd::erase_if_present(hexes, ap.from);
  545. vstd::erase_if_present(hexes, ap.attack.attacker->occupiedHex(ap.attack.attackerPos));
  546. }
  547. float notRealizedDamage = 0;
  548. for(auto unit : attackers)
  549. {
  550. if(unit->unitId() == ap.attack.attacker->unitId())
  551. continue;
  552. if(!vstd::contains_if(hexes, [&](BattleHex h) -> bool
  553. {
  554. return vstd::contains(reachabilityMap[h], unit);
  555. }))
  556. {
  557. notRealizedDamage += attackerValue[unit->unitId()].value;
  558. continue;
  559. }
  560. auto desiredPosition = vstd::minElementByFun(hexes, [&](BattleHex h) -> float
  561. {
  562. auto score = vstd::contains(reachabilityMap[h], unit)
  563. ? reachabilityMap[h].size()
  564. : 0;
  565. if(unit->doubleWide())
  566. {
  567. auto backHex = unit->occupiedHex(h);
  568. if(vstd::contains(hexes, backHex))
  569. score += reachabilityMap[backHex].size();
  570. }
  571. return score;
  572. });
  573. hexes.erase(desiredPosition);
  574. }
  575. if(notRealizedDamage > ap.attackValue() && notRealizedDamage > attackerValue[ap.attack.attacker->unitId()].value)
  576. {
  577. dpsScore = BattleScore(EvaluationResult::INEFFECTIVE_SCORE, 0);
  578. }
  579. }
  580. bool BattleExchangeEvaluator::canBeHitThisTurn(const AttackPossibility & ap)
  581. {
  582. for(auto pos : ap.attack.attacker->getSurroundingHexes())
  583. {
  584. for(auto u : reachabilityMap[pos])
  585. {
  586. if(u->unitSide() != ap.attack.attacker->unitSide())
  587. {
  588. return true;
  589. }
  590. }
  591. }
  592. return false;
  593. }
  594. void BattleExchangeEvaluator::updateReachabilityMap( std::shared_ptr<HypotheticBattle> hb)
  595. {
  596. const int TURN_DEPTH = 2;
  597. turnOrder.clear();
  598. hb->battleGetTurnOrder(turnOrder, std::numeric_limits<int>::max(), TURN_DEPTH);
  599. reachabilityMap.clear();
  600. for(int turn = 0; turn < turnOrder.size(); turn++)
  601. {
  602. auto & turnQueue = turnOrder[turn];
  603. HypotheticBattle turnBattle(env.get(), cb);
  604. for(const battle::Unit * unit : turnQueue)
  605. {
  606. if(unit->isTurret())
  607. continue;
  608. auto unitSpeed = unit->speed(turn);
  609. if(turnBattle.battleCanShoot(unit))
  610. {
  611. for(BattleHex hex = BattleHex::TOP_LEFT; hex.isValid(); hex = hex + 1)
  612. {
  613. reachabilityMap[hex].push_back(unit);
  614. }
  615. continue;
  616. }
  617. auto unitReachability = turnBattle.getReachability(unit);
  618. for(BattleHex hex = BattleHex::TOP_LEFT; hex.isValid(); hex = hex + 1)
  619. {
  620. bool reachable = unitReachability.distances[hex] <= unitSpeed;
  621. if(!reachable && unitReachability.accessibility[hex] == EAccessibility::ALIVE_STACK)
  622. {
  623. const battle::Unit * hexStack = cb->battleGetUnitByPos(hex);
  624. if(hexStack && cb->battleMatchOwner(unit, hexStack, false))
  625. {
  626. for(BattleHex neighbor : hex.neighbouringTiles())
  627. {
  628. reachable = unitReachability.distances[neighbor] <= unitSpeed;
  629. if(reachable) break;
  630. }
  631. }
  632. }
  633. if(reachable)
  634. {
  635. reachabilityMap[hex].push_back(unit);
  636. }
  637. }
  638. }
  639. }
  640. }
  641. // avoid blocking path for stronger stack by weaker stack
  642. bool BattleExchangeEvaluator::checkPositionBlocksOurStacks(HypotheticBattle & hb, const battle::Unit * activeUnit, BattleHex position)
  643. {
  644. const int BLOCKING_THRESHOLD = 70;
  645. const int BLOCKING_OWN_ATTACK_PENALTY = 100;
  646. const int BLOCKING_OWN_MOVE_PENALTY = 1;
  647. float blockingScore = 0;
  648. auto activeUnitDamage = activeUnit->getMinDamage(hb.battleCanShoot(activeUnit)) * activeUnit->getCount();
  649. for(int turn = 0; turn < turnOrder.size(); turn++)
  650. {
  651. auto & turnQueue = turnOrder[turn];
  652. HypotheticBattle turnBattle(env.get(), cb);
  653. auto unitToUpdate = turnBattle.getForUpdate(activeUnit->unitId());
  654. unitToUpdate->setPosition(position);
  655. for(const battle::Unit * unit : turnQueue)
  656. {
  657. if(unit->unitId() == unitToUpdate->unitId() || cb->battleMatchOwner(unit, activeUnit, false))
  658. continue;
  659. auto blockedUnitDamage = unit->getMinDamage(hb.battleCanShoot(unit)) * unit->getCount();
  660. auto ratio = blockedUnitDamage / (blockedUnitDamage + activeUnitDamage);
  661. auto unitReachability = turnBattle.getReachability(unit);
  662. for(BattleHex hex = BattleHex::TOP_LEFT; hex.isValid(); hex = hex + 1)
  663. {
  664. bool enemyUnit = false;
  665. bool reachable = unitReachability.distances[hex] <= unit->speed(turn);
  666. if(!reachable && unitReachability.accessibility[hex] == EAccessibility::ALIVE_STACK)
  667. {
  668. const battle::Unit * hexStack = turnBattle.battleGetUnitByPos(hex);
  669. if(hexStack && cb->battleMatchOwner(unit, hexStack, false))
  670. {
  671. enemyUnit = true;
  672. for(BattleHex neighbor : hex.neighbouringTiles())
  673. {
  674. reachable = unitReachability.distances[neighbor] <= unit->speed(turn);
  675. if(reachable) break;
  676. }
  677. }
  678. }
  679. if(!reachable && vstd::contains(reachabilityMap[hex], unit))
  680. {
  681. blockingScore += ratio * (enemyUnit ? BLOCKING_OWN_ATTACK_PENALTY : BLOCKING_OWN_MOVE_PENALTY);
  682. }
  683. }
  684. }
  685. }
  686. #if BATTLE_TRACE_LEVEL>=1
  687. logAi->trace("Position %d, blocking score %f", position.hex, blockingScore);
  688. #endif
  689. return blockingScore > BLOCKING_THRESHOLD;
  690. }