BattleExchangeVariant.cpp 22 KB

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