BattleExchangeVariant.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994
  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)
  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. ReachabilityInfo getReachabilityWithEnemyBypass(
  239. const battle::Unit * activeStack,
  240. DamageCache & damageCache,
  241. std::shared_ptr<HypotheticBattle> state)
  242. {
  243. ReachabilityInfo::Parameters params(activeStack, activeStack->getPosition());
  244. if(!params.flying)
  245. {
  246. for(const auto * unit : state->battleAliveUnits())
  247. {
  248. if(unit->unitSide() == activeStack->unitSide())
  249. continue;
  250. auto dmg = damageCache.getOriginalDamage(activeStack, unit, state);
  251. auto turnsToKill = unit->getAvailableHealth() / dmg;
  252. vstd::amin(turnsToKill, 100);
  253. for(auto & hex : unit->getHexes())
  254. if(hex.isAvailable()) //towers can have <0 pos; we don't also want to overwrite side columns
  255. params.destructibleEnemyTurns[hex] = turnsToKill * unit->getMovementRange();
  256. }
  257. params.bypassEnemyStacks = true;
  258. }
  259. return state->getReachability(params);
  260. }
  261. MoveTarget BattleExchangeEvaluator::findMoveTowardsUnreachable(
  262. const battle::Unit * activeStack,
  263. PotentialTargets & targets,
  264. DamageCache & damageCache,
  265. std::shared_ptr<HypotheticBattle> hb)
  266. {
  267. MoveTarget result;
  268. BattleExchangeVariant ev;
  269. logAi->trace("Find move towards unreachable. Enemies count %d", targets.unreachableEnemies.size());
  270. if(targets.unreachableEnemies.empty())
  271. return result;
  272. auto speed = activeStack->getMovementRange();
  273. if(speed == 0)
  274. return result;
  275. updateReachabilityMap(hb);
  276. auto dists = getReachabilityWithEnemyBypass(activeStack, damageCache, hb);
  277. auto flying = activeStack->hasBonusOfType(BonusType::FLYING);
  278. for(const battle::Unit * enemy : targets.unreachableEnemies)
  279. {
  280. logAi->trace(
  281. "Checking movement towards %d of %s",
  282. enemy->getCount(),
  283. enemy->creatureId().toCreature()->getNameSingularTranslated());
  284. auto distance = dists.distToNearestNeighbour(activeStack, enemy);
  285. if(distance >= GameConstants::BFIELD_SIZE)
  286. continue;
  287. if(distance <= speed)
  288. continue;
  289. auto turnsToRich = (distance - 1) / speed + 1;
  290. auto hexes = enemy->getSurroundingHexes();
  291. auto enemySpeed = enemy->getMovementRange();
  292. auto speedRatio = speed / static_cast<float>(enemySpeed);
  293. auto multiplier = speedRatio > 1 ? 1 : speedRatio;
  294. for(auto & hex : hexes)
  295. {
  296. // FIXME: provide distance info for Jousting bonus
  297. auto bai = BattleAttackInfo(activeStack, enemy, 0, cb->battleCanShoot(activeStack));
  298. auto attack = AttackPossibility::evaluate(bai, hex, damageCache, hb);
  299. attack.shootersBlockedDmg = 0; // we do not want to count on it, it is not for sure
  300. auto score = calculateExchange(attack, turnsToRich, targets, damageCache, hb);
  301. score.enemyDamageReduce *= multiplier;
  302. #if BATTLE_TRACE_LEVEL >= 1
  303. logAi->trace("Multiplier: %f, turns: %d, current score %f, new score %f", multiplier, turnsToRich, result.score, scoreValue(score));
  304. #endif
  305. if(result.score < scoreValue(score)
  306. || (result.turnsToRich > turnsToRich && vstd::isAlmostEqual(result.score, scoreValue(score))))
  307. {
  308. result.score = scoreValue(score);
  309. result.positions.clear();
  310. #if BATTLE_TRACE_LEVEL >= 1
  311. logAi->trace("New high score");
  312. #endif
  313. for(BattleHex enemyHex : enemy->getAttackableHexes(activeStack))
  314. {
  315. while(!flying && dists.distances[enemyHex] > speed)
  316. {
  317. enemyHex = dists.predecessors.at(enemyHex);
  318. if(dists.accessibility[enemyHex] == EAccessibility::ALIVE_STACK)
  319. {
  320. auto defenderToBypass = hb->battleGetUnitByPos(enemyHex);
  321. if(defenderToBypass)
  322. {
  323. #if BATTLE_TRACE_LEVEL >= 1
  324. logAi->trace("Found target to bypass at %d", enemyHex.hex);
  325. #endif
  326. auto attackHex = dists.predecessors[enemyHex];
  327. auto baiBypass = BattleAttackInfo(activeStack, defenderToBypass, 0, cb->battleCanShoot(activeStack));
  328. auto attackBypass = AttackPossibility::evaluate(baiBypass, attackHex, damageCache, hb);
  329. auto adjacentStacks = getAdjacentUnits(enemy);
  330. adjacentStacks.push_back(defenderToBypass);
  331. vstd::removeDuplicates(adjacentStacks);
  332. auto bypassScore = calculateExchange(
  333. attackBypass,
  334. dists.distances[attackHex],
  335. targets,
  336. damageCache,
  337. hb,
  338. adjacentStacks);
  339. if(scoreValue(bypassScore) > result.score)
  340. {
  341. result.score = scoreValue(bypassScore);
  342. #if BATTLE_TRACE_LEVEL >= 1
  343. logAi->trace("New high score after bypass %f", scoreValue(bypassScore));
  344. #endif
  345. }
  346. }
  347. }
  348. }
  349. result.positions.push_back(enemyHex);
  350. }
  351. result.cachedAttack = attack;
  352. result.turnsToRich = turnsToRich;
  353. }
  354. }
  355. }
  356. return result;
  357. }
  358. std::vector<const battle::Unit *> BattleExchangeEvaluator::getAdjacentUnits(const battle::Unit * blockerUnit) const
  359. {
  360. std::queue<const battle::Unit *> queue;
  361. std::vector<const battle::Unit *> checkedStacks;
  362. queue.push(blockerUnit);
  363. while(!queue.empty())
  364. {
  365. auto stack = queue.front();
  366. queue.pop();
  367. checkedStacks.push_back(stack);
  368. auto hexes = stack->getSurroundingHexes();
  369. for(auto hex : hexes)
  370. {
  371. auto neighbor = cb->battleGetUnitByPos(hex);
  372. if(neighbor && neighbor->unitSide() == stack->unitSide() && !vstd::contains(checkedStacks, neighbor))
  373. {
  374. queue.push(neighbor);
  375. checkedStacks.push_back(neighbor);
  376. }
  377. }
  378. }
  379. return checkedStacks;
  380. }
  381. ReachabilityData BattleExchangeEvaluator::getExchangeUnits(
  382. const AttackPossibility & ap,
  383. uint8_t turn,
  384. PotentialTargets & targets,
  385. std::shared_ptr<HypotheticBattle> hb,
  386. std::vector<const battle::Unit *> additionalUnits) const
  387. {
  388. ReachabilityData result;
  389. auto hexes = ap.attack.defender->getSurroundingHexes();
  390. if(!ap.attack.shooting) hexes.push_back(ap.from);
  391. std::vector<const battle::Unit *> allReachableUnits = additionalUnits;
  392. for(auto hex : hexes)
  393. {
  394. vstd::concatenate(allReachableUnits, turn == 0 ? reachabilityMap.at(hex) : getOneTurnReachableUnits(turn, hex));
  395. }
  396. for(auto hex : ap.attack.attacker->getHexes())
  397. {
  398. auto unitsReachingAttacker = turn == 0 ? reachabilityMap.at(hex) : getOneTurnReachableUnits(turn, hex);
  399. for(auto unit : unitsReachingAttacker)
  400. {
  401. if(unit->unitSide() != ap.attack.attacker->unitSide())
  402. {
  403. allReachableUnits.push_back(unit);
  404. result.enemyUnitsReachingAttacker.insert(unit->unitId());
  405. }
  406. }
  407. }
  408. vstd::removeDuplicates(allReachableUnits);
  409. auto copy = allReachableUnits;
  410. for(auto unit : copy)
  411. {
  412. for(auto adjacentUnit : getAdjacentUnits(unit))
  413. {
  414. auto unitWithBonuses = hb->battleGetUnitByID(adjacentUnit->unitId());
  415. if(vstd::contains(targets.unreachableEnemies, adjacentUnit)
  416. && !vstd::contains(allReachableUnits, unitWithBonuses))
  417. {
  418. allReachableUnits.push_back(unitWithBonuses);
  419. }
  420. }
  421. }
  422. vstd::removeDuplicates(allReachableUnits);
  423. if(!vstd::contains(allReachableUnits, ap.attack.attacker))
  424. {
  425. allReachableUnits.push_back(ap.attack.attacker);
  426. }
  427. if(allReachableUnits.size() < 2)
  428. {
  429. #if BATTLE_TRACE_LEVEL>=1
  430. logAi->trace("Reachability map contains only %d stacks", allReachableUnits.size());
  431. #endif
  432. return result;
  433. }
  434. for(auto unit : allReachableUnits)
  435. {
  436. auto accessible = !unit->canShoot() || vstd::contains(additionalUnits, unit);
  437. if(!accessible)
  438. {
  439. for(auto hex : unit->getSurroundingHexes())
  440. {
  441. if(ap.attack.defender->coversPos(hex))
  442. {
  443. accessible = true;
  444. }
  445. }
  446. }
  447. if(accessible)
  448. result.melleeAccessible.push_back(unit);
  449. else
  450. result.shooters.push_back(unit);
  451. }
  452. for(int turn = 0; turn < turnOrder.size(); turn++)
  453. {
  454. for(auto unit : turnOrder[turn])
  455. {
  456. if(vstd::contains(allReachableUnits, unit))
  457. result.units[turn].push_back(unit);
  458. }
  459. vstd::erase_if(result.units[turn], [&](const battle::Unit * u) -> bool
  460. {
  461. return !hb->battleGetUnitByID(u->unitId())->alive();
  462. });
  463. }
  464. return result;
  465. }
  466. float BattleExchangeEvaluator::evaluateExchange(
  467. const AttackPossibility & ap,
  468. uint8_t turn,
  469. PotentialTargets & targets,
  470. DamageCache & damageCache,
  471. std::shared_ptr<HypotheticBattle> hb) const
  472. {
  473. BattleScore score = calculateExchange(ap, turn, targets, damageCache, hb);
  474. #if BATTLE_TRACE_LEVEL >= 1
  475. logAi->trace(
  476. "calculateExchange score +%2f -%2fx%2f = %2f",
  477. score.enemyDamageReduce,
  478. score.ourDamageReduce,
  479. getNegativeEffectMultiplier(),
  480. scoreValue(score));
  481. #endif
  482. return scoreValue(score);
  483. }
  484. BattleScore BattleExchangeEvaluator::calculateExchange(
  485. const AttackPossibility & ap,
  486. uint8_t turn,
  487. PotentialTargets & targets,
  488. DamageCache & damageCache,
  489. std::shared_ptr<HypotheticBattle> hb,
  490. std::vector<const battle::Unit *> additionalUnits) const
  491. {
  492. #if BATTLE_TRACE_LEVEL>=1
  493. logAi->trace("Battle exchange at %d", ap.attack.shooting ? ap.dest.hex : ap.from.hex);
  494. #endif
  495. if(cb->battleGetMySide() == BattleSide::LEFT_SIDE
  496. && cb->battleGetGateState() == EGateState::BLOCKED
  497. && ap.attack.defender->coversPos(BattleHex::GATE_BRIDGE))
  498. {
  499. return BattleScore(EvaluationResult::INEFFECTIVE_SCORE, 0);
  500. }
  501. std::vector<const battle::Unit *> ourStacks;
  502. std::vector<const battle::Unit *> enemyStacks;
  503. if(hb->battleGetUnitByID(ap.attack.defender->unitId())->alive())
  504. enemyStacks.push_back(ap.attack.defender);
  505. ReachabilityData exchangeUnits = getExchangeUnits(ap, turn, targets, hb, additionalUnits);
  506. if(exchangeUnits.units.empty())
  507. {
  508. return BattleScore();
  509. }
  510. auto exchangeBattle = std::make_shared<HypotheticBattle>(env.get(), hb);
  511. BattleExchangeVariant v;
  512. for(int exchangeTurn = 0; exchangeTurn < exchangeUnits.units.size(); exchangeTurn++)
  513. {
  514. for(auto unit : exchangeUnits.units.at(exchangeTurn))
  515. {
  516. if(unit->isTurret())
  517. continue;
  518. bool isOur = exchangeBattle->battleMatchOwner(ap.attack.attacker, unit, true);
  519. auto & attackerQueue = isOur ? ourStacks : enemyStacks;
  520. auto u = exchangeBattle->getForUpdate(unit->unitId());
  521. if(u->alive() && !vstd::contains(attackerQueue, unit))
  522. {
  523. attackerQueue.push_back(unit);
  524. #if BATTLE_TRACE_LEVEL
  525. logAi->trace("Exchanging: %s", u->getDescription());
  526. #endif
  527. }
  528. }
  529. }
  530. auto melleeAttackers = ourStacks;
  531. vstd::removeDuplicates(melleeAttackers);
  532. vstd::erase_if(melleeAttackers, [&](const battle::Unit * u) -> bool
  533. {
  534. return cb->battleCanShoot(u);
  535. });
  536. bool canUseAp = true;
  537. const int totalTurnsCount = 10;
  538. std::set<uint32_t> blockedShooters;
  539. for(int exchangeTurn = 0; exchangeTurn < totalTurnsCount; exchangeTurn++)
  540. {
  541. bool isMovingTurm = exchangeTurn < turn;
  542. int queueTurn = exchangeTurn >= exchangeUnits.units.size()
  543. ? exchangeUnits.units.size() - 1
  544. : exchangeTurn;
  545. for(auto activeUnit : exchangeUnits.units.at(queueTurn))
  546. {
  547. bool isOur = exchangeBattle->battleMatchOwner(ap.attack.attacker, activeUnit, true);
  548. battle::Units & attackerQueue = isOur ? ourStacks : enemyStacks;
  549. battle::Units & oppositeQueue = isOur ? enemyStacks : ourStacks;
  550. auto attacker = exchangeBattle->getForUpdate(activeUnit->unitId());
  551. auto shooting = exchangeBattle->battleCanShoot(attacker.get())
  552. && !vstd::contains(blockedShooters, attacker->unitId());
  553. if(!attacker->alive())
  554. {
  555. #if BATTLE_TRACE_LEVEL>=1
  556. logAi->trace("Attacker is dead");
  557. #endif
  558. continue;
  559. }
  560. if(isMovingTurm && !shooting
  561. && !vstd::contains(exchangeUnits.enemyUnitsReachingAttacker, attacker->unitId()))
  562. {
  563. #if BATTLE_TRACE_LEVEL>=1
  564. logAi->trace("Attacker is moving");
  565. #endif
  566. continue;
  567. }
  568. auto targetUnit = ap.attack.defender;
  569. if(!isOur || !exchangeBattle->battleGetUnitByID(targetUnit->unitId())->alive())
  570. {
  571. #if BATTLE_TRACE_LEVEL>=2
  572. logAi->trace("Best target selector for %s", attacker->getDescription());
  573. #endif
  574. auto estimateAttack = [&](const battle::Unit * u) -> float
  575. {
  576. auto stackWithBonuses = exchangeBattle->getForUpdate(u->unitId());
  577. auto score = v.trackAttack(
  578. attacker,
  579. stackWithBonuses,
  580. exchangeBattle->battleCanShoot(stackWithBonuses.get()),
  581. isOur,
  582. damageCache,
  583. hb,
  584. true);
  585. #if BATTLE_TRACE_LEVEL>=2
  586. logAi->trace("Best target selector %s->%s score = %2f", attacker->getDescription(), stackWithBonuses->getDescription(), score);
  587. #endif
  588. return score;
  589. };
  590. auto unitsInOppositeQueueExceptInaccessible = oppositeQueue;
  591. vstd::erase_if(unitsInOppositeQueueExceptInaccessible, [&](const battle::Unit * u)->bool
  592. {
  593. return vstd::contains(exchangeUnits.shooters, u);
  594. });
  595. if(!unitsInOppositeQueueExceptInaccessible.empty())
  596. {
  597. targetUnit = *vstd::maxElementByFun(unitsInOppositeQueueExceptInaccessible, estimateAttack);
  598. }
  599. else
  600. {
  601. auto reachable = exchangeBattle->battleGetUnitsIf([this, &exchangeBattle, &attacker](const battle::Unit * u) -> bool
  602. {
  603. if(u->unitSide() == attacker->unitSide())
  604. return false;
  605. if(!exchangeBattle->getForUpdate(u->unitId())->alive())
  606. return false;
  607. if(!u->getPosition().isValid())
  608. return false; // e.g. tower shooters
  609. return vstd::contains_if(reachabilityMap.at(u->getPosition()), [&attacker](const battle::Unit * other) -> bool
  610. {
  611. return attacker->unitId() == other->unitId();
  612. });
  613. });
  614. if(!reachable.empty())
  615. {
  616. targetUnit = *vstd::maxElementByFun(reachable, estimateAttack);
  617. }
  618. else
  619. {
  620. #if BATTLE_TRACE_LEVEL>=1
  621. logAi->trace("Battle queue is empty and no reachable enemy.");
  622. #endif
  623. continue;
  624. }
  625. }
  626. }
  627. auto defender = exchangeBattle->getForUpdate(targetUnit->unitId());
  628. const int totalAttacks = attacker->getTotalAttacks(shooting);
  629. if(canUseAp && activeUnit->unitId() == ap.attack.attacker->unitId()
  630. && targetUnit->unitId() == ap.attack.defender->unitId())
  631. {
  632. v.trackAttack(ap, exchangeBattle, damageCache);
  633. }
  634. else
  635. {
  636. for(int i = 0; i < totalAttacks; i++)
  637. {
  638. v.trackAttack(attacker, defender, shooting, isOur, damageCache, exchangeBattle);
  639. if(!attacker->alive() || !defender->alive())
  640. break;
  641. }
  642. }
  643. if(!shooting)
  644. blockedShooters.insert(defender->unitId());
  645. canUseAp = false;
  646. vstd::erase_if(attackerQueue, [&](const battle::Unit * u) -> bool
  647. {
  648. return !exchangeBattle->battleGetUnitByID(u->unitId())->alive();
  649. });
  650. vstd::erase_if(oppositeQueue, [&](const battle::Unit * u) -> bool
  651. {
  652. return !exchangeBattle->battleGetUnitByID(u->unitId())->alive();
  653. });
  654. }
  655. exchangeBattle->nextRound();
  656. }
  657. // avoid blocking path for stronger stack by weaker stack
  658. // the method checks if all stacks can be placed around enemy
  659. std::map<BattleHex, battle::Units> reachabilityMap;
  660. auto hexes = ap.attack.defender->getSurroundingHexes();
  661. for(auto hex : hexes)
  662. reachabilityMap[hex] = getOneTurnReachableUnits(turn, hex);
  663. auto score = v.getScore();
  664. if(turn > 0)
  665. {
  666. auto turnMultiplier = 1 - std::min(0.2, 0.05 * turn);
  667. score.enemyDamageReduce *= turnMultiplier;
  668. }
  669. #if BATTLE_TRACE_LEVEL>=1
  670. logAi->trace("Exchange score: enemy: %2f, our -%2f", score.enemyDamageReduce, score.ourDamageReduce);
  671. #endif
  672. return score;
  673. }
  674. bool BattleExchangeEvaluator::canBeHitThisTurn(const AttackPossibility & ap)
  675. {
  676. for(auto pos : ap.attack.attacker->getSurroundingHexes())
  677. {
  678. for(auto u : reachabilityMap[pos])
  679. {
  680. if(u->unitSide() != ap.attack.attacker->unitSide())
  681. {
  682. return true;
  683. }
  684. }
  685. }
  686. return false;
  687. }
  688. void BattleExchangeEvaluator::updateReachabilityMap(std::shared_ptr<HypotheticBattle> hb)
  689. {
  690. const int TURN_DEPTH = 2;
  691. turnOrder.clear();
  692. hb->battleGetTurnOrder(turnOrder, std::numeric_limits<int>::max(), TURN_DEPTH);
  693. for(auto turn : turnOrder)
  694. {
  695. for(auto u : turn)
  696. {
  697. if(!vstd::contains(reachabilityCache, u->unitId()))
  698. {
  699. reachabilityCache[u->unitId()] = hb->getReachability(u);
  700. }
  701. }
  702. }
  703. for(BattleHex hex = BattleHex::TOP_LEFT; hex.isValid(); hex = hex + 1)
  704. {
  705. reachabilityMap[hex] = getOneTurnReachableUnits(0, hex);
  706. }
  707. }
  708. std::vector<const battle::Unit *> BattleExchangeEvaluator::getOneTurnReachableUnits(uint8_t turn, BattleHex hex) const
  709. {
  710. std::vector<const battle::Unit *> result;
  711. for(int i = 0; i < turnOrder.size(); i++)
  712. {
  713. auto & turnQueue = turnOrder[i];
  714. HypotheticBattle turnBattle(env.get(), cb);
  715. for(const battle::Unit * unit : turnQueue)
  716. {
  717. if(unit->isTurret())
  718. continue;
  719. if(turnBattle.battleCanShoot(unit))
  720. {
  721. result.push_back(unit);
  722. continue;
  723. }
  724. auto unitSpeed = unit->getMovementRange(turn);
  725. auto radius = unitSpeed * (turn + 1);
  726. auto reachabilityIter = reachabilityCache.find(unit->unitId());
  727. assert(reachabilityIter != reachabilityCache.end()); // missing updateReachabilityMap call?
  728. ReachabilityInfo unitReachability = reachabilityIter != reachabilityCache.end() ? reachabilityIter->second : turnBattle.getReachability(unit);
  729. bool reachable = unitReachability.distances[hex] <= radius;
  730. if(!reachable && unitReachability.accessibility[hex] == EAccessibility::ALIVE_STACK)
  731. {
  732. const battle::Unit * hexStack = cb->battleGetUnitByPos(hex);
  733. if(hexStack && cb->battleMatchOwner(unit, hexStack, false))
  734. {
  735. for(BattleHex neighbor : hex.neighbouringTiles())
  736. {
  737. reachable = unitReachability.distances[neighbor] <= radius;
  738. if(reachable) break;
  739. }
  740. }
  741. }
  742. if(reachable)
  743. {
  744. result.push_back(unit);
  745. }
  746. }
  747. }
  748. return result;
  749. }
  750. // avoid blocking path for stronger stack by weaker stack
  751. bool BattleExchangeEvaluator::checkPositionBlocksOurStacks(HypotheticBattle & hb, const battle::Unit * activeUnit, BattleHex position)
  752. {
  753. const int BLOCKING_THRESHOLD = 70;
  754. const int BLOCKING_OWN_ATTACK_PENALTY = 100;
  755. const int BLOCKING_OWN_MOVE_PENALTY = 1;
  756. float blockingScore = 0;
  757. auto activeUnitDamage = activeUnit->getMinDamage(hb.battleCanShoot(activeUnit)) * activeUnit->getCount();
  758. for(int turn = 0; turn < turnOrder.size(); turn++)
  759. {
  760. auto & turnQueue = turnOrder[turn];
  761. HypotheticBattle turnBattle(env.get(), cb);
  762. auto unitToUpdate = turnBattle.getForUpdate(activeUnit->unitId());
  763. unitToUpdate->setPosition(position);
  764. for(const battle::Unit * unit : turnQueue)
  765. {
  766. if(unit->unitId() == unitToUpdate->unitId() || cb->battleMatchOwner(unit, activeUnit, false))
  767. continue;
  768. auto blockedUnitDamage = unit->getMinDamage(hb.battleCanShoot(unit)) * unit->getCount();
  769. float ratio = blockedUnitDamage / (float)(blockedUnitDamage + activeUnitDamage + 0.01);
  770. auto unitReachability = turnBattle.getReachability(unit);
  771. auto unitSpeed = unit->getMovementRange(turn); // Cached value, to avoid performance hit
  772. for(BattleHex hex = BattleHex::TOP_LEFT; hex.isValid(); hex = hex + 1)
  773. {
  774. bool enemyUnit = false;
  775. bool reachable = unitReachability.distances[hex] <= unitSpeed;
  776. if(!reachable && unitReachability.accessibility[hex] == EAccessibility::ALIVE_STACK)
  777. {
  778. const battle::Unit * hexStack = turnBattle.battleGetUnitByPos(hex);
  779. if(hexStack && cb->battleMatchOwner(unit, hexStack, false))
  780. {
  781. enemyUnit = true;
  782. for(BattleHex neighbor : hex.neighbouringTiles())
  783. {
  784. reachable = unitReachability.distances[neighbor] <= unitSpeed;
  785. if(reachable) break;
  786. }
  787. }
  788. }
  789. if(!reachable && std::count(reachabilityMap[hex].begin(), reachabilityMap[hex].end(), unit) > 1)
  790. {
  791. blockingScore += ratio * (enemyUnit ? BLOCKING_OWN_ATTACK_PENALTY : BLOCKING_OWN_MOVE_PENALTY);
  792. }
  793. }
  794. }
  795. }
  796. #if BATTLE_TRACE_LEVEL>=1
  797. logAi->trace("Position %d, blocking score %f", position.hex, blockingScore);
  798. #endif
  799. return blockingScore > BLOCKING_THRESHOLD;
  800. }