BattleExchangeVariant.cpp 21 KB

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