2023-08-19 09:22:34 +02:00
|
|
|
/*
|
|
|
|
* BattleAI.cpp, part of VCMI engine
|
|
|
|
*
|
|
|
|
* Authors: listed in file AUTHORS in main folder
|
|
|
|
*
|
|
|
|
* License: GNU General Public License v2.0 or later
|
|
|
|
* Full text of license available in license.txt file, in main folder
|
|
|
|
*
|
|
|
|
*/
|
|
|
|
#include "StdInc.h"
|
|
|
|
#include "BattleEvaluator.h"
|
|
|
|
#include "BattleExchangeVariant.h"
|
|
|
|
|
|
|
|
#include "StackWithBonuses.h"
|
|
|
|
#include "EnemyInfo.h"
|
|
|
|
#include "tbb/parallel_for.h"
|
|
|
|
#include "../../lib/CStopWatch.h"
|
|
|
|
#include "../../lib/CThreadHelper.h"
|
|
|
|
#include "../../lib/mapObjects/CGTownInstance.h"
|
2024-08-28 21:33:56 +02:00
|
|
|
#include "../../lib/entities/building/TownFortifications.h"
|
2023-08-19 09:22:34 +02:00
|
|
|
#include "../../lib/spells/CSpellHandler.h"
|
|
|
|
#include "../../lib/spells/ISpellMechanics.h"
|
|
|
|
#include "../../lib/battle/BattleStateInfoForRetreat.h"
|
|
|
|
#include "../../lib/battle/CObstacleInstance.h"
|
|
|
|
#include "../../lib/battle/BattleAction.h"
|
2024-01-31 00:17:40 +02:00
|
|
|
#include "../../lib/CRandomGenerator.h"
|
|
|
|
|
2023-08-19 09:22:34 +02:00
|
|
|
|
|
|
|
// TODO: remove
|
|
|
|
// Eventually only IBattleInfoCallback and battle::Unit should be used,
|
|
|
|
// CUnitState should be private and CStack should be removed completely
|
|
|
|
#include "../../lib/CStack.h"
|
|
|
|
|
|
|
|
#define LOGL(text) print(text)
|
|
|
|
#define LOGFL(text, formattingEl) print(boost::str(boost::format(text) % formattingEl))
|
|
|
|
|
|
|
|
enum class SpellTypes
|
|
|
|
{
|
|
|
|
ADVENTURE, BATTLE, OTHER
|
|
|
|
};
|
|
|
|
|
|
|
|
SpellTypes spellType(const CSpell * spell)
|
|
|
|
{
|
|
|
|
if(!spell->isCombat() || spell->isCreatureAbility())
|
|
|
|
return SpellTypes::OTHER;
|
|
|
|
|
|
|
|
if(spell->isOffensive() || spell->hasEffects() || spell->hasBattleEffects())
|
|
|
|
return SpellTypes::BATTLE;
|
|
|
|
|
|
|
|
return SpellTypes::OTHER;
|
|
|
|
}
|
|
|
|
|
2024-08-21 21:18:26 +02:00
|
|
|
BattleEvaluator::BattleEvaluator(
|
|
|
|
std::shared_ptr<Environment> env,
|
|
|
|
std::shared_ptr<CBattleCallback> cb,
|
|
|
|
const battle::Unit * activeStack,
|
|
|
|
PlayerColor playerID,
|
|
|
|
BattleID battleID,
|
|
|
|
BattleSide side,
|
|
|
|
float strengthRatio,
|
|
|
|
int simulationTurnsCount)
|
|
|
|
:scoreEvaluator(cb->getBattle(battleID), env, strengthRatio, simulationTurnsCount),
|
|
|
|
cachedAttack(), playerID(playerID), side(side), env(env),
|
|
|
|
cb(cb), strengthRatio(strengthRatio), battleID(battleID), simulationTurnsCount(simulationTurnsCount)
|
|
|
|
{
|
|
|
|
hb = std::make_shared<HypotheticBattle>(env.get(), cb->getBattle(battleID));
|
|
|
|
damageCache.buildDamageCache(hb, side);
|
|
|
|
|
|
|
|
targets = std::make_unique<PotentialTargets>(activeStack, damageCache, hb);
|
|
|
|
}
|
|
|
|
|
|
|
|
BattleEvaluator::BattleEvaluator(
|
|
|
|
std::shared_ptr<Environment> env,
|
|
|
|
std::shared_ptr<CBattleCallback> cb,
|
|
|
|
std::shared_ptr<HypotheticBattle> hb,
|
|
|
|
DamageCache & damageCache,
|
|
|
|
const battle::Unit * activeStack,
|
|
|
|
PlayerColor playerID,
|
|
|
|
BattleID battleID,
|
|
|
|
BattleSide side,
|
|
|
|
float strengthRatio,
|
|
|
|
int simulationTurnsCount)
|
|
|
|
:scoreEvaluator(cb->getBattle(battleID), env, strengthRatio, simulationTurnsCount),
|
|
|
|
cachedAttack(), playerID(playerID), side(side), env(env), cb(cb), hb(hb),
|
|
|
|
damageCache(damageCache), strengthRatio(strengthRatio), battleID(battleID), simulationTurnsCount(simulationTurnsCount)
|
|
|
|
{
|
|
|
|
targets = std::make_unique<PotentialTargets>(activeStack, damageCache, hb);
|
|
|
|
}
|
|
|
|
|
2023-08-19 09:22:34 +02:00
|
|
|
std::vector<BattleHex> BattleEvaluator::getBrokenWallMoatHexes() const
|
|
|
|
{
|
|
|
|
std::vector<BattleHex> result;
|
|
|
|
|
|
|
|
for(EWallPart wallPart : { EWallPart::BOTTOM_WALL, EWallPart::BELOW_GATE, EWallPart::OVER_GATE, EWallPart::UPPER_WALL })
|
|
|
|
{
|
2023-08-28 17:59:12 +02:00
|
|
|
auto state = cb->getBattle(battleID)->battleGetWallState(wallPart);
|
2023-08-19 09:22:34 +02:00
|
|
|
|
|
|
|
if(state != EWallState::DESTROYED)
|
|
|
|
continue;
|
|
|
|
|
2023-10-27 19:23:54 +02:00
|
|
|
auto wallHex = cb->getBattle(battleID)->wallPartToBattleHex(wallPart);
|
2023-08-19 09:22:34 +02:00
|
|
|
auto moatHex = wallHex.cloneInDirection(BattleHex::LEFT);
|
|
|
|
|
|
|
|
result.push_back(moatHex);
|
2024-04-20 14:26:52 +02:00
|
|
|
|
|
|
|
moatHex = moatHex.cloneInDirection(BattleHex::LEFT);
|
|
|
|
auto obstaclesSecondRow = cb->getBattle(battleID)->battleGetAllObstaclesOnPos(moatHex, false);
|
|
|
|
|
|
|
|
for(auto obstacle : obstaclesSecondRow)
|
|
|
|
{
|
|
|
|
if(obstacle->obstacleType == CObstacleInstance::EObstacleType::MOAT)
|
|
|
|
{
|
|
|
|
result.push_back(moatHex);
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
2023-08-19 09:22:34 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
2024-12-05 22:09:24 +02:00
|
|
|
bool BattleEvaluator::hasWorkingTowers() const
|
|
|
|
{
|
|
|
|
bool keepIntact = cb->getBattle(battleID)->battleGetWallState(EWallPart::KEEP) != EWallState::NONE && cb->getBattle(battleID)->battleGetWallState(EWallPart::KEEP) != EWallState::DESTROYED;
|
|
|
|
bool upperIntact = cb->getBattle(battleID)->battleGetWallState(EWallPart::UPPER_TOWER) != EWallState::NONE && cb->getBattle(battleID)->battleGetWallState(EWallPart::UPPER_TOWER) != EWallState::DESTROYED;
|
|
|
|
bool bottomIntact = cb->getBattle(battleID)->battleGetWallState(EWallPart::BOTTOM_TOWER) != EWallState::NONE && cb->getBattle(battleID)->battleGetWallState(EWallPart::BOTTOM_TOWER) != EWallState::DESTROYED;
|
|
|
|
return keepIntact || upperIntact || bottomIntact;
|
|
|
|
}
|
|
|
|
|
2023-08-19 09:22:34 +02:00
|
|
|
std::optional<PossibleSpellcast> BattleEvaluator::findBestCreatureSpell(const CStack *stack)
|
|
|
|
{
|
|
|
|
//TODO: faerie dragon type spell should be selected by server
|
2023-12-24 01:10:05 +02:00
|
|
|
SpellID creatureSpellToCast = cb->getBattle(battleID)->getRandomCastedSpell(CRandomGenerator::getDefault(), stack);
|
|
|
|
|
|
|
|
if(stack->canCast() && creatureSpellToCast != SpellID::NONE)
|
2023-08-19 09:22:34 +02:00
|
|
|
{
|
|
|
|
const CSpell * spell = creatureSpellToCast.toSpell();
|
|
|
|
|
2023-08-28 17:59:12 +02:00
|
|
|
if(spell->canBeCast(cb->getBattle(battleID).get(), spells::Mode::CREATURE_ACTIVE, stack))
|
2023-08-19 09:22:34 +02:00
|
|
|
{
|
|
|
|
std::vector<PossibleSpellcast> possibleCasts;
|
2023-08-28 17:59:12 +02:00
|
|
|
spells::BattleCast temp(cb->getBattle(battleID).get(), stack, spells::Mode::CREATURE_ACTIVE, spell);
|
2023-08-19 09:22:34 +02:00
|
|
|
for(auto & target : temp.findPotentialTargets())
|
|
|
|
{
|
|
|
|
PossibleSpellcast ps;
|
|
|
|
ps.dest = target;
|
|
|
|
ps.spell = spell;
|
|
|
|
evaluateCreatureSpellcast(stack, ps);
|
|
|
|
possibleCasts.push_back(ps);
|
|
|
|
}
|
|
|
|
|
|
|
|
std::sort(possibleCasts.begin(), possibleCasts.end(), [&](const PossibleSpellcast & lhs, const PossibleSpellcast & rhs) { return lhs.value > rhs.value; });
|
|
|
|
if(!possibleCasts.empty() && possibleCasts.front().value > 0)
|
|
|
|
{
|
|
|
|
return possibleCasts.front();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return std::nullopt;
|
|
|
|
}
|
|
|
|
|
|
|
|
BattleAction BattleEvaluator::selectStackAction(const CStack * stack)
|
|
|
|
{
|
2023-08-26 12:06:41 +02:00
|
|
|
#if BATTLE_TRACE_LEVEL >= 1
|
|
|
|
logAi->trace("Select stack action");
|
|
|
|
#endif
|
2023-08-19 09:22:34 +02:00
|
|
|
//evaluate casting spell for spellcasting stack
|
|
|
|
std::optional<PossibleSpellcast> bestSpellcast = findBestCreatureSpell(stack);
|
|
|
|
|
|
|
|
auto moveTarget = scoreEvaluator.findMoveTowardsUnreachable(stack, *targets, damageCache, hb);
|
2023-08-26 12:06:41 +02:00
|
|
|
float score = EvaluationResult::INEFFECTIVE_SCORE;
|
2024-12-05 22:09:24 +02:00
|
|
|
auto enemyMellee = hb->getUnitsIf([this](const battle::Unit* u) -> bool
|
|
|
|
{
|
|
|
|
return u->unitSide() == BattleSide::ATTACKER && !hb->battleCanShoot(u);
|
|
|
|
});
|
|
|
|
bool siegeDefense = stack->unitSide() == BattleSide::DEFENDER
|
|
|
|
&& !stack->canShoot()
|
|
|
|
&& hasWorkingTowers()
|
|
|
|
&& !enemyMellee.empty();
|
2023-08-19 09:22:34 +02:00
|
|
|
|
|
|
|
if(targets->possibleAttacks.empty() && bestSpellcast.has_value())
|
|
|
|
{
|
|
|
|
activeActionMade = true;
|
|
|
|
return BattleAction::makeCreatureSpellcast(stack, bestSpellcast->dest, bestSpellcast->spell->id);
|
|
|
|
}
|
|
|
|
|
|
|
|
if(!targets->possibleAttacks.empty())
|
|
|
|
{
|
|
|
|
#if BATTLE_TRACE_LEVEL>=1
|
|
|
|
logAi->trace("Evaluating attack for %s", stack->getDescription());
|
|
|
|
#endif
|
|
|
|
|
2024-12-05 22:09:24 +02:00
|
|
|
auto evaluationResult = scoreEvaluator.findBestTarget(stack, *targets, damageCache, hb, siegeDefense);
|
2023-08-19 09:22:34 +02:00
|
|
|
auto & bestAttack = evaluationResult.bestAttack;
|
|
|
|
|
2024-08-25 14:49:11 +02:00
|
|
|
cachedAttack.ap = bestAttack;
|
|
|
|
cachedAttack.score = evaluationResult.score;
|
|
|
|
cachedAttack.turn = 0;
|
|
|
|
cachedAttack.waited = evaluationResult.wait;
|
2023-08-19 09:22:34 +02:00
|
|
|
|
|
|
|
//TODO: consider more complex spellcast evaluation, f.e. because "re-retaliation" during enemy move in same turn for melee attack etc.
|
|
|
|
if(bestSpellcast.has_value() && bestSpellcast->value > bestAttack.damageDiff())
|
|
|
|
{
|
|
|
|
// return because spellcast value is damage dealt and score is dps reduce
|
|
|
|
activeActionMade = true;
|
|
|
|
return BattleAction::makeCreatureSpellcast(stack, bestSpellcast->dest, bestSpellcast->spell->id);
|
|
|
|
}
|
|
|
|
|
|
|
|
if(evaluationResult.score > score)
|
|
|
|
{
|
|
|
|
score = evaluationResult.score;
|
|
|
|
|
2023-08-26 12:06:41 +02:00
|
|
|
logAi->debug("BattleAI: %s -> %s x %d, from %d curpos %d dist %d speed %d: +%2f -%2f = %2f",
|
2023-08-19 09:22:34 +02:00
|
|
|
bestAttack.attackerState->unitType()->getJsonKey(),
|
|
|
|
bestAttack.affectedUnits[0]->unitType()->getJsonKey(),
|
2023-10-27 19:23:54 +02:00
|
|
|
bestAttack.affectedUnits[0]->getCount(),
|
2023-08-19 09:22:34 +02:00
|
|
|
(int)bestAttack.from,
|
|
|
|
(int)bestAttack.attack.attacker->getPosition().hex,
|
|
|
|
bestAttack.attack.chargeDistance,
|
2024-01-14 17:14:36 +02:00
|
|
|
bestAttack.attack.attacker->getMovementRange(0),
|
2023-08-19 09:22:34 +02:00
|
|
|
bestAttack.defenderDamageReduce,
|
2023-08-26 12:06:41 +02:00
|
|
|
bestAttack.attackerDamageReduce,
|
2023-10-13 21:04:26 +02:00
|
|
|
score
|
2023-08-19 09:22:34 +02:00
|
|
|
);
|
|
|
|
|
2024-08-17 17:17:46 +02:00
|
|
|
if (moveTarget.score <= score)
|
2023-08-19 09:22:34 +02:00
|
|
|
{
|
|
|
|
if(evaluationResult.wait)
|
|
|
|
{
|
|
|
|
return BattleAction::makeWait(stack);
|
|
|
|
}
|
|
|
|
else if(bestAttack.attack.shooting)
|
|
|
|
{
|
|
|
|
activeActionMade = true;
|
|
|
|
return BattleAction::makeShotAttack(stack, bestAttack.attack.defender);
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
if(bestAttack.collateralDamageReduce
|
|
|
|
&& bestAttack.collateralDamageReduce >= bestAttack.defenderDamageReduce / 2
|
|
|
|
&& score < 0)
|
|
|
|
{
|
|
|
|
return BattleAction::makeDefend(stack);
|
|
|
|
}
|
2024-09-02 13:24:22 +02:00
|
|
|
|
2024-12-14 16:39:09 +02:00
|
|
|
bool isTargetOutsideFort = !hb->battleIsInsideWalls(bestAttack.from);
|
2024-09-02 13:24:22 +02:00
|
|
|
bool siegeDefense = stack->unitSide() == BattleSide::DEFENDER
|
|
|
|
&& !bestAttack.attack.shooting
|
2024-12-05 22:09:24 +02:00
|
|
|
&& hasWorkingTowers()
|
2024-09-02 13:24:22 +02:00
|
|
|
&& !enemyMellee.empty()
|
|
|
|
&& isTargetOutsideFort;
|
|
|
|
|
|
|
|
if(siegeDefense)
|
2023-08-19 09:22:34 +02:00
|
|
|
{
|
2024-09-02 13:24:22 +02:00
|
|
|
logAi->trace("Evaluating exchange at %d self-defense", stack->getPosition().hex);
|
|
|
|
|
|
|
|
BattleAttackInfo bai(stack, stack, 0, false);
|
|
|
|
AttackPossibility apDefend(stack->getPosition(), stack->getPosition(), bai);
|
|
|
|
|
|
|
|
float defenseValue = scoreEvaluator.evaluateExchange(apDefend, 0, *targets, damageCache, hb);
|
|
|
|
|
|
|
|
if((defenseValue > score && score <= 0) || (defenseValue > 2 * score && score > 0))
|
|
|
|
{
|
|
|
|
return BattleAction::makeDefend(stack);
|
|
|
|
}
|
2023-08-19 09:22:34 +02:00
|
|
|
}
|
2024-09-02 13:24:22 +02:00
|
|
|
|
|
|
|
activeActionMade = true;
|
|
|
|
return BattleAction::makeMeleeAttack(stack, bestAttack.attack.defenderPos, bestAttack.from);
|
2023-08-19 09:22:34 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-06-24 03:23:26 +02:00
|
|
|
//ThreatMap threatsToUs(stack); // These lines may be useful but they are't used in the code.
|
2024-08-17 17:17:46 +02:00
|
|
|
if(moveTarget.score > score)
|
2023-08-19 09:22:34 +02:00
|
|
|
{
|
|
|
|
score = moveTarget.score;
|
2024-08-25 14:49:11 +02:00
|
|
|
cachedAttack.ap = moveTarget.cachedAttack;
|
|
|
|
cachedAttack.score = score;
|
|
|
|
cachedAttack.turn = moveTarget.turnsToRich;
|
2023-08-19 09:22:34 +02:00
|
|
|
|
|
|
|
if(stack->waited())
|
|
|
|
{
|
2023-10-03 07:16:12 +02:00
|
|
|
logAi->debug(
|
2024-08-17 17:17:46 +02:00
|
|
|
"Moving %s towards hex %s[%d], score: %2f",
|
2023-10-03 07:16:12 +02:00
|
|
|
stack->getDescription(),
|
|
|
|
moveTarget.cachedAttack->attack.defender->getDescription(),
|
|
|
|
moveTarget.cachedAttack->attack.defender->getPosition().hex,
|
2024-08-17 17:17:46 +02:00
|
|
|
moveTarget.score);
|
2023-10-03 07:16:12 +02:00
|
|
|
|
2024-07-19 12:44:44 +02:00
|
|
|
return goTowardsNearest(stack, moveTarget.positions, *targets);
|
2023-08-19 09:22:34 +02:00
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
2024-08-25 14:49:11 +02:00
|
|
|
cachedAttack.waited = true;
|
|
|
|
|
2023-08-19 09:22:34 +02:00
|
|
|
return BattleAction::makeWait(stack);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if(score <= EvaluationResult::INEFFECTIVE_SCORE
|
|
|
|
&& !stack->hasBonusOfType(BonusType::FLYING)
|
|
|
|
&& stack->unitSide() == BattleSide::ATTACKER
|
2024-08-28 21:33:56 +02:00
|
|
|
&& cb->getBattle(battleID)->battleGetFortifications().hasMoat)
|
2023-08-19 09:22:34 +02:00
|
|
|
{
|
|
|
|
auto brokenWallMoat = getBrokenWallMoatHexes();
|
|
|
|
|
|
|
|
if(brokenWallMoat.size())
|
|
|
|
{
|
|
|
|
activeActionMade = true;
|
|
|
|
|
|
|
|
if(stack->doubleWide() && vstd::contains(brokenWallMoat, stack->getPosition()))
|
|
|
|
return BattleAction::makeMove(stack, stack->getPosition().cloneInDirection(BattleHex::RIGHT));
|
|
|
|
else
|
2024-07-19 12:44:44 +02:00
|
|
|
return goTowardsNearest(stack, brokenWallMoat, *targets);
|
2023-08-19 09:22:34 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-01-14 10:23:44 +02:00
|
|
|
return stack->waited() ? BattleAction::makeDefend(stack) : BattleAction::makeWait(stack);
|
2023-08-19 09:22:34 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
uint64_t timeElapsed(std::chrono::time_point<std::chrono::high_resolution_clock> start)
|
|
|
|
{
|
|
|
|
auto end = std::chrono::high_resolution_clock::now();
|
|
|
|
|
|
|
|
return std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
|
|
|
|
}
|
|
|
|
|
2024-07-21 18:56:52 +02:00
|
|
|
BattleAction BattleEvaluator::moveOrAttack(const CStack * stack, BattleHex hex, const PotentialTargets & targets)
|
|
|
|
{
|
|
|
|
auto additionalScore = 0;
|
|
|
|
std::optional<AttackPossibility> attackOnTheWay;
|
|
|
|
|
|
|
|
for(auto & target : targets.possibleAttacks)
|
|
|
|
{
|
|
|
|
if(!target.attack.shooting && target.from == hex && target.attackValue() > additionalScore)
|
|
|
|
{
|
|
|
|
additionalScore = target.attackValue();
|
|
|
|
attackOnTheWay = target;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if(attackOnTheWay)
|
|
|
|
{
|
|
|
|
activeActionMade = true;
|
|
|
|
return BattleAction::makeMeleeAttack(stack, attackOnTheWay->attack.defender->getPosition(), attackOnTheWay->from);
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
2024-09-19 20:54:50 +02:00
|
|
|
if(stack->position == hex)
|
|
|
|
return BattleAction::makeDefend(stack);
|
|
|
|
else
|
|
|
|
return BattleAction::makeMove(stack, hex);
|
2024-07-21 18:56:52 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-07-19 12:44:44 +02:00
|
|
|
BattleAction BattleEvaluator::goTowardsNearest(const CStack * stack, std::vector<BattleHex> hexes, const PotentialTargets & targets)
|
2023-08-19 09:22:34 +02:00
|
|
|
{
|
2023-08-28 17:59:12 +02:00
|
|
|
auto reachability = cb->getBattle(battleID)->getReachability(stack);
|
|
|
|
auto avHexes = cb->getBattle(battleID)->battleGetAvailableHexes(reachability, stack, false);
|
2023-08-19 09:22:34 +02:00
|
|
|
|
2024-12-05 22:09:24 +02:00
|
|
|
auto enemyMellee = hb->getUnitsIf([this](const battle::Unit* u) -> bool
|
|
|
|
{
|
|
|
|
return u->unitSide() == BattleSide::ATTACKER && !hb->battleCanShoot(u);
|
|
|
|
});
|
|
|
|
|
|
|
|
bool siegeDefense = stack->unitSide() == BattleSide::DEFENDER
|
|
|
|
&& hasWorkingTowers()
|
|
|
|
&& !enemyMellee.empty();
|
|
|
|
|
|
|
|
if (siegeDefense)
|
|
|
|
{
|
|
|
|
vstd::erase_if(avHexes, [&](const BattleHex& hex) {
|
2024-12-14 16:39:09 +02:00
|
|
|
return !cb->getBattle(battleID)->battleIsInsideWalls(hex);
|
|
|
|
});
|
2024-12-05 22:09:24 +02:00
|
|
|
}
|
|
|
|
|
2023-08-19 09:22:34 +02:00
|
|
|
if(!avHexes.size() || !hexes.size()) //we are blocked or dest is blocked
|
|
|
|
{
|
|
|
|
return BattleAction::makeDefend(stack);
|
|
|
|
}
|
|
|
|
|
2024-06-18 19:03:07 +02:00
|
|
|
std::vector<BattleHex> targetHexes = hexes;
|
2023-08-19 09:22:34 +02:00
|
|
|
|
2024-07-21 18:56:52 +02:00
|
|
|
vstd::erase_if(targetHexes, [](const BattleHex & hex) { return !hex.isValid(); });
|
2024-06-18 19:03:07 +02:00
|
|
|
|
2024-07-21 18:56:52 +02:00
|
|
|
std::sort(targetHexes.begin(), targetHexes.end(), [&](BattleHex h1, BattleHex h2) -> bool
|
2023-08-19 09:22:34 +02:00
|
|
|
{
|
2024-07-21 18:56:52 +02:00
|
|
|
return reachability.distances[h1] < reachability.distances[h2];
|
|
|
|
});
|
2023-08-19 09:22:34 +02:00
|
|
|
|
2024-06-18 19:03:07 +02:00
|
|
|
BattleHex bestNeighbor = targetHexes.front();
|
2023-08-19 09:22:34 +02:00
|
|
|
|
|
|
|
if(reachability.distances[bestNeighbor] > GameConstants::BFIELD_SIZE)
|
|
|
|
{
|
2024-07-21 18:56:52 +02:00
|
|
|
logAi->trace("No richable hexes.");
|
2023-08-19 09:22:34 +02:00
|
|
|
return BattleAction::makeDefend(stack);
|
|
|
|
}
|
|
|
|
|
2024-07-21 18:56:52 +02:00
|
|
|
// this turn
|
|
|
|
for(auto hex : targetHexes)
|
|
|
|
{
|
|
|
|
if(vstd::contains(avHexes, hex))
|
|
|
|
{
|
|
|
|
return moveOrAttack(stack, hex, targets);
|
2024-06-18 19:03:07 +02:00
|
|
|
}
|
|
|
|
|
2024-07-21 18:56:52 +02:00
|
|
|
if(stack->coversPos(hex))
|
2024-06-18 19:03:07 +02:00
|
|
|
{
|
2024-07-21 18:56:52 +02:00
|
|
|
logAi->warn("Warning: already standing on neighbouring hex!");
|
|
|
|
//We shouldn't even be here...
|
|
|
|
return BattleAction::makeDefend(stack);
|
2023-08-19 09:22:34 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-07-21 18:56:52 +02:00
|
|
|
// not this turn
|
2023-08-19 09:22:34 +02:00
|
|
|
scoreEvaluator.updateReachabilityMap(hb);
|
|
|
|
|
|
|
|
if(stack->hasBonusOfType(BonusType::FLYING))
|
|
|
|
{
|
|
|
|
std::set<BattleHex> obstacleHexes;
|
|
|
|
|
2024-10-03 23:03:36 +02:00
|
|
|
auto insertAffected = [](const CObstacleInstance & spellObst, std::set<BattleHex> & obstacleHexes) {
|
2023-08-19 09:22:34 +02:00
|
|
|
auto affectedHexes = spellObst.getAffectedTiles();
|
|
|
|
obstacleHexes.insert(affectedHexes.cbegin(), affectedHexes.cend());
|
|
|
|
};
|
|
|
|
|
|
|
|
const auto & obstacles = hb->battleGetAllObstacles();
|
|
|
|
|
|
|
|
for (const auto & obst: obstacles) {
|
|
|
|
|
|
|
|
if(obst->triggersEffects())
|
|
|
|
{
|
|
|
|
auto triggerAbility = VLC->spells()->getById(obst->getTrigger());
|
|
|
|
auto triggerIsNegative = triggerAbility->isNegative() || triggerAbility->isDamage();
|
|
|
|
|
|
|
|
if(triggerIsNegative)
|
|
|
|
insertAffected(*obst, obstacleHexes);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// Flying stack doesn't go hex by hex, so we can't backtrack using predecessors.
|
|
|
|
// We just check all available hexes and pick the one closest to the target.
|
|
|
|
auto nearestAvailableHex = vstd::minElementByFun(avHexes, [&](BattleHex hex) -> int
|
|
|
|
{
|
|
|
|
const int NEGATIVE_OBSTACLE_PENALTY = 100; // avoid landing on negative obstacle (moat, fire wall, etc)
|
|
|
|
const int BLOCKED_STACK_PENALTY = 100; // avoid landing on moat
|
|
|
|
|
|
|
|
auto distance = BattleHex::getDistance(bestNeighbor, hex);
|
|
|
|
|
|
|
|
if(vstd::contains(obstacleHexes, hex))
|
|
|
|
distance += NEGATIVE_OBSTACLE_PENALTY;
|
|
|
|
|
|
|
|
return scoreEvaluator.checkPositionBlocksOurStacks(*hb, stack, hex) ? BLOCKED_STACK_PENALTY + distance : distance;
|
|
|
|
});
|
|
|
|
|
2024-07-21 18:56:52 +02:00
|
|
|
return moveOrAttack(stack, *nearestAvailableHex, targets);
|
2023-08-19 09:22:34 +02:00
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
BattleHex currentDest = bestNeighbor;
|
2023-10-28 20:01:37 +02:00
|
|
|
while(true)
|
2023-08-19 09:22:34 +02:00
|
|
|
{
|
|
|
|
if(!currentDest.isValid())
|
|
|
|
{
|
|
|
|
return BattleAction::makeDefend(stack);
|
|
|
|
}
|
|
|
|
|
|
|
|
if(vstd::contains(avHexes, currentDest)
|
|
|
|
&& !scoreEvaluator.checkPositionBlocksOurStacks(*hb, stack, currentDest))
|
2024-07-21 18:56:52 +02:00
|
|
|
{
|
|
|
|
return moveOrAttack(stack, currentDest, targets);
|
|
|
|
}
|
2023-08-19 09:22:34 +02:00
|
|
|
|
|
|
|
currentDest = reachability.predecessors[currentDest];
|
|
|
|
}
|
|
|
|
}
|
2024-07-21 18:56:52 +02:00
|
|
|
|
|
|
|
logAi->error("We should either detect that hexes are unreachable or make a move!");
|
|
|
|
return BattleAction::makeDefend(stack);
|
2023-08-19 09:22:34 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
bool BattleEvaluator::canCastSpell()
|
|
|
|
{
|
2023-08-28 17:59:12 +02:00
|
|
|
auto hero = cb->getBattle(battleID)->battleGetMyHero();
|
2023-08-19 09:22:34 +02:00
|
|
|
if(!hero)
|
|
|
|
return false;
|
|
|
|
|
2023-08-28 17:59:12 +02:00
|
|
|
return cb->getBattle(battleID)->battleCanCastSpell(hero, spells::Mode::HERO) == ESpellCastProblem::OK;
|
2023-08-19 09:22:34 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
bool BattleEvaluator::attemptCastingSpell(const CStack * activeStack)
|
|
|
|
{
|
2023-08-28 17:59:12 +02:00
|
|
|
auto hero = cb->getBattle(battleID)->battleGetMyHero();
|
2023-08-19 09:22:34 +02:00
|
|
|
if(!hero)
|
|
|
|
return false;
|
|
|
|
|
|
|
|
LOGL("Casting spells sounds like fun. Let's see...");
|
|
|
|
//Get all spells we can cast
|
|
|
|
std::vector<const CSpell*> possibleSpells;
|
2023-12-31 23:43:35 +02:00
|
|
|
|
|
|
|
for (auto const & s : VLC->spellh->objects)
|
|
|
|
if (s->canBeCast(cb->getBattle(battleID).get(), spells::Mode::HERO, hero))
|
|
|
|
possibleSpells.push_back(s.get());
|
|
|
|
|
2023-08-19 09:22:34 +02:00
|
|
|
LOGFL("I can cast %d spells.", possibleSpells.size());
|
|
|
|
|
|
|
|
vstd::erase_if(possibleSpells, [](const CSpell *s)
|
|
|
|
{
|
2024-07-10 02:40:42 +02:00
|
|
|
return spellType(s) != SpellTypes::BATTLE;
|
2023-08-19 09:22:34 +02:00
|
|
|
});
|
|
|
|
|
|
|
|
LOGFL("I know how %d of them works.", possibleSpells.size());
|
|
|
|
|
|
|
|
//Get possible spell-target pairs
|
|
|
|
std::vector<PossibleSpellcast> possibleCasts;
|
|
|
|
for(auto spell : possibleSpells)
|
|
|
|
{
|
2023-08-28 17:59:12 +02:00
|
|
|
spells::BattleCast temp(cb->getBattle(battleID).get(), hero, spells::Mode::HERO, spell);
|
2023-08-19 09:22:34 +02:00
|
|
|
|
|
|
|
const bool FAST = true;
|
|
|
|
|
|
|
|
for(auto & target : temp.findPotentialTargets(FAST))
|
|
|
|
{
|
|
|
|
PossibleSpellcast ps;
|
|
|
|
ps.dest = target;
|
|
|
|
ps.spell = spell;
|
|
|
|
possibleCasts.push_back(ps);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
LOGFL("Found %d spell-target combinations.", possibleCasts.size());
|
|
|
|
if(possibleCasts.empty())
|
|
|
|
return false;
|
|
|
|
|
|
|
|
using ValueMap = PossibleSpellcast::ValueMap;
|
|
|
|
|
|
|
|
auto evaluateQueue = [&](ValueMap & values, const std::vector<battle::Units> & queue, std::shared_ptr<HypotheticBattle> state, size_t minTurnSpan, bool * enemyHadTurnOut) -> bool
|
|
|
|
{
|
|
|
|
bool firstRound = true;
|
|
|
|
bool enemyHadTurn = false;
|
|
|
|
size_t ourTurnSpan = 0;
|
|
|
|
|
|
|
|
bool stop = false;
|
|
|
|
|
|
|
|
for(auto & round : queue)
|
|
|
|
{
|
|
|
|
if(!firstRound)
|
2023-08-28 16:43:57 +02:00
|
|
|
state->nextRound();
|
2023-08-19 09:22:34 +02:00
|
|
|
for(auto unit : round)
|
|
|
|
{
|
|
|
|
if(!vstd::contains(values, unit->unitId()))
|
|
|
|
values[unit->unitId()] = 0;
|
|
|
|
|
|
|
|
if(!unit->alive())
|
|
|
|
continue;
|
|
|
|
|
|
|
|
if(state->battleGetOwner(unit) != playerID)
|
|
|
|
{
|
|
|
|
enemyHadTurn = true;
|
|
|
|
|
|
|
|
if(!firstRound || state->battleCastSpells(unit->unitSide()) == 0)
|
|
|
|
{
|
|
|
|
//enemy could counter our spell at this point
|
|
|
|
//anyway, we do not know what enemy will do
|
|
|
|
//just stop evaluation
|
|
|
|
stop = true;
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
else if(!enemyHadTurn)
|
|
|
|
{
|
|
|
|
ourTurnSpan++;
|
|
|
|
}
|
|
|
|
|
|
|
|
state->nextTurn(unit->unitId());
|
|
|
|
|
2023-12-19 20:52:40 +02:00
|
|
|
PotentialTargets potentialTargets(unit, damageCache, state);
|
2023-08-19 09:22:34 +02:00
|
|
|
|
2023-12-19 20:52:40 +02:00
|
|
|
if(!potentialTargets.possibleAttacks.empty())
|
2023-08-19 09:22:34 +02:00
|
|
|
{
|
2023-12-19 20:52:40 +02:00
|
|
|
AttackPossibility attackPossibility = potentialTargets.bestAction();
|
2023-08-19 09:22:34 +02:00
|
|
|
|
2023-12-19 20:52:40 +02:00
|
|
|
auto stackWithBonuses = state->getForUpdate(unit->unitId());
|
|
|
|
*stackWithBonuses = *attackPossibility.attackerState;
|
2023-08-19 09:22:34 +02:00
|
|
|
|
2023-12-19 20:52:40 +02:00
|
|
|
if(attackPossibility.defenderDamageReduce > 0)
|
|
|
|
{
|
|
|
|
stackWithBonuses->removeUnitBonus(Bonus::UntilAttack);
|
|
|
|
stackWithBonuses->removeUnitBonus(Bonus::UntilOwnAttack);
|
|
|
|
}
|
|
|
|
if(attackPossibility.attackerDamageReduce > 0)
|
|
|
|
stackWithBonuses->removeUnitBonus(Bonus::UntilBeingAttacked);
|
2023-08-19 09:22:34 +02:00
|
|
|
|
2023-12-19 20:52:40 +02:00
|
|
|
for(auto affected : attackPossibility.affectedUnits)
|
2023-08-19 09:22:34 +02:00
|
|
|
{
|
2023-12-19 20:52:40 +02:00
|
|
|
stackWithBonuses = state->getForUpdate(affected->unitId());
|
|
|
|
*stackWithBonuses = *affected;
|
2023-08-19 09:22:34 +02:00
|
|
|
|
2023-12-19 20:52:40 +02:00
|
|
|
if(attackPossibility.defenderDamageReduce > 0)
|
|
|
|
stackWithBonuses->removeUnitBonus(Bonus::UntilBeingAttacked);
|
|
|
|
if(attackPossibility.attackerDamageReduce > 0 && attackPossibility.attack.defender->unitId() == affected->unitId())
|
|
|
|
stackWithBonuses->removeUnitBonus(Bonus::UntilAttack);
|
2023-08-19 09:22:34 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-12-19 20:52:40 +02:00
|
|
|
auto bav = potentialTargets.bestActionValue();
|
2023-08-19 09:22:34 +02:00
|
|
|
|
|
|
|
//best action is from effective owner`s point if view, we need to convert to our point if view
|
|
|
|
if(state->battleGetOwner(unit) != playerID)
|
|
|
|
bav = -bav;
|
|
|
|
values[unit->unitId()] += bav;
|
|
|
|
}
|
|
|
|
|
|
|
|
firstRound = false;
|
|
|
|
|
|
|
|
if(stop)
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
|
|
|
if(enemyHadTurnOut)
|
|
|
|
*enemyHadTurnOut = enemyHadTurn;
|
|
|
|
|
|
|
|
return ourTurnSpan >= minTurnSpan;
|
|
|
|
};
|
|
|
|
|
|
|
|
ValueMap valueOfStack;
|
|
|
|
ValueMap healthOfStack;
|
|
|
|
|
2023-08-28 17:59:12 +02:00
|
|
|
TStacks all = cb->getBattle(battleID)->battleGetAllStacks(false);
|
2023-08-19 09:22:34 +02:00
|
|
|
|
|
|
|
size_t ourRemainingTurns = 0;
|
|
|
|
|
|
|
|
for(auto unit : all)
|
|
|
|
{
|
|
|
|
healthOfStack[unit->unitId()] = unit->getAvailableHealth();
|
|
|
|
valueOfStack[unit->unitId()] = 0;
|
|
|
|
|
2023-08-28 17:59:12 +02:00
|
|
|
if(cb->getBattle(battleID)->battleGetOwner(unit) == playerID && unit->canMove() && !unit->moved())
|
2023-08-19 09:22:34 +02:00
|
|
|
ourRemainingTurns++;
|
|
|
|
}
|
|
|
|
|
|
|
|
LOGFL("I have %d turns left in this round", ourRemainingTurns);
|
|
|
|
|
|
|
|
const bool castNow = ourRemainingTurns <= 1;
|
|
|
|
|
|
|
|
if(castNow)
|
|
|
|
print("I should try to cast a spell now");
|
|
|
|
else
|
|
|
|
print("I could wait better moment to cast a spell");
|
|
|
|
|
|
|
|
auto amount = all.size();
|
|
|
|
|
|
|
|
std::vector<battle::Units> turnOrder;
|
|
|
|
|
2023-08-28 17:59:12 +02:00
|
|
|
cb->getBattle(battleID)->battleGetTurnOrder(turnOrder, amount, 2); //no more than 1 turn after current, each unit at least once
|
2023-08-19 09:22:34 +02:00
|
|
|
|
|
|
|
{
|
|
|
|
bool enemyHadTurn = false;
|
|
|
|
|
2023-08-28 17:59:12 +02:00
|
|
|
auto state = std::make_shared<HypotheticBattle>(env.get(), cb->getBattle(battleID));
|
2023-08-19 09:22:34 +02:00
|
|
|
|
|
|
|
evaluateQueue(valueOfStack, turnOrder, state, 0, &enemyHadTurn);
|
|
|
|
|
|
|
|
if(!enemyHadTurn)
|
|
|
|
{
|
|
|
|
auto battleIsFinishedOpt = state->battleIsFinished();
|
|
|
|
|
|
|
|
if(battleIsFinishedOpt)
|
|
|
|
{
|
|
|
|
print("No need to cast a spell. Battle will finish soon.");
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
CStopWatch timer;
|
|
|
|
|
2023-08-26 12:06:41 +02:00
|
|
|
#if BATTLE_TRACE_LEVEL >= 1
|
|
|
|
tbb::blocked_range<size_t> r(0, possibleCasts.size());
|
|
|
|
#else
|
2023-08-19 09:22:34 +02:00
|
|
|
tbb::parallel_for(tbb::blocked_range<size_t>(0, possibleCasts.size()), [&](const tbb::blocked_range<size_t> & r)
|
|
|
|
{
|
2023-08-26 12:06:41 +02:00
|
|
|
#endif
|
2023-08-19 09:22:34 +02:00
|
|
|
for(auto i = r.begin(); i != r.end(); i++)
|
|
|
|
{
|
|
|
|
auto & ps = possibleCasts[i];
|
2023-08-26 12:06:41 +02:00
|
|
|
|
|
|
|
#if BATTLE_TRACE_LEVEL >= 1
|
2024-08-26 10:30:39 +02:00
|
|
|
if(ps.dest.empty())
|
|
|
|
logAi->trace("Evaluating %s", ps.spell->getNameTranslated());
|
|
|
|
else
|
|
|
|
{
|
|
|
|
auto psFirst = ps.dest.front();
|
|
|
|
auto strWhere = psFirst.unitValue ? psFirst.unitValue->getDescription() : std::to_string(psFirst.hexValue.hex);
|
|
|
|
|
|
|
|
logAi->trace("Evaluating %s at %s", ps.spell->getNameTranslated(), strWhere);
|
|
|
|
}
|
2023-08-26 12:06:41 +02:00
|
|
|
#endif
|
|
|
|
|
2023-08-28 17:59:12 +02:00
|
|
|
auto state = std::make_shared<HypotheticBattle>(env.get(), cb->getBattle(battleID));
|
2023-08-19 09:22:34 +02:00
|
|
|
|
|
|
|
spells::BattleCast cast(state.get(), hero, spells::Mode::HERO, ps.spell);
|
|
|
|
cast.castEval(state->getServerCallback(), ps.dest);
|
|
|
|
|
2024-07-10 02:40:42 +02:00
|
|
|
auto allUnits = state->battleGetUnitsIf([](const battle::Unit * u) -> bool { return u->isValidTarget(); });
|
2023-08-19 09:22:34 +02:00
|
|
|
|
|
|
|
auto needFullEval = vstd::contains_if(allUnits, [&](const battle::Unit * u) -> bool
|
|
|
|
{
|
2023-08-28 17:59:12 +02:00
|
|
|
auto original = cb->getBattle(battleID)->battleGetUnitByID(u->unitId());
|
2024-01-14 17:14:36 +02:00
|
|
|
return !original || u->getMovementRange() != original->getMovementRange();
|
2023-08-19 09:22:34 +02:00
|
|
|
});
|
|
|
|
|
2023-08-26 12:06:41 +02:00
|
|
|
DamageCache safeCopy = damageCache;
|
|
|
|
DamageCache innerCache(&safeCopy);
|
2024-08-25 14:49:11 +02:00
|
|
|
|
2023-08-19 09:22:34 +02:00
|
|
|
innerCache.buildDamageCache(state, side);
|
|
|
|
|
2024-08-25 14:49:11 +02:00
|
|
|
if(cachedAttack.ap && cachedAttack.waited)
|
|
|
|
{
|
|
|
|
state->makeWait(activeStack);
|
|
|
|
}
|
|
|
|
|
|
|
|
if(needFullEval || !cachedAttack.ap)
|
2023-08-19 09:22:34 +02:00
|
|
|
{
|
2023-08-26 12:06:41 +02:00
|
|
|
#if BATTLE_TRACE_LEVEL >= 1
|
|
|
|
logAi->trace("Full evaluation is started due to stack speed affected.");
|
|
|
|
#endif
|
|
|
|
|
|
|
|
PotentialTargets innerTargets(activeStack, innerCache, state);
|
2024-08-21 21:18:26 +02:00
|
|
|
BattleExchangeEvaluator innerEvaluator(state, env, strengthRatio, simulationTurnsCount);
|
2023-08-19 09:22:34 +02:00
|
|
|
|
2024-08-25 14:49:11 +02:00
|
|
|
innerEvaluator.updateReachabilityMap(state);
|
|
|
|
|
2024-08-26 10:30:39 +02:00
|
|
|
auto moveTarget = innerEvaluator.findMoveTowardsUnreachable(activeStack, innerTargets, innerCache, state);
|
2024-08-25 14:49:11 +02:00
|
|
|
|
2023-08-19 09:22:34 +02:00
|
|
|
if(!innerTargets.possibleAttacks.empty())
|
|
|
|
{
|
|
|
|
auto newStackAction = innerEvaluator.findBestTarget(activeStack, innerTargets, innerCache, state);
|
|
|
|
|
2024-08-25 14:49:11 +02:00
|
|
|
ps.value = std::max(moveTarget.score, newStackAction.score);
|
2023-08-19 09:22:34 +02:00
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
2024-08-25 14:49:11 +02:00
|
|
|
ps.value = moveTarget.score;
|
2023-08-19 09:22:34 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
2024-08-26 10:30:39 +02:00
|
|
|
auto updatedAttacker = state->getForUpdate(cachedAttack.ap->attack.attacker->unitId());
|
|
|
|
auto updatedDefender = state->getForUpdate(cachedAttack.ap->attack.defender->unitId());
|
|
|
|
auto updatedBai = BattleAttackInfo(
|
|
|
|
updatedAttacker.get(),
|
|
|
|
updatedDefender.get(),
|
|
|
|
cachedAttack.ap->attack.chargeDistance,
|
|
|
|
cachedAttack.ap->attack.shooting);
|
|
|
|
|
|
|
|
auto updatedAttack = AttackPossibility::evaluate(updatedBai, cachedAttack.ap->from, innerCache, state);
|
|
|
|
|
|
|
|
ps.value = scoreEvaluator.evaluateExchange(updatedAttack, cachedAttack.turn, *targets, innerCache, state);
|
2023-08-19 09:22:34 +02:00
|
|
|
}
|
2024-07-10 02:40:42 +02:00
|
|
|
for(const auto & unit : allUnits)
|
|
|
|
{
|
2024-08-26 10:30:39 +02:00
|
|
|
if(!unit->isValidTarget(true))
|
2024-07-09 22:55:39 +02:00
|
|
|
continue;
|
2024-08-25 14:49:11 +02:00
|
|
|
|
2023-08-19 09:22:34 +02:00
|
|
|
auto newHealth = unit->getAvailableHealth();
|
2024-06-17 17:28:30 +02:00
|
|
|
auto oldHealth = vstd::find_or(healthOfStack, unit->unitId(), 0); // old health value may not exist for newly summoned units
|
2023-08-19 09:22:34 +02:00
|
|
|
|
|
|
|
if(oldHealth != newHealth)
|
|
|
|
{
|
|
|
|
auto damage = std::abs(oldHealth - newHealth);
|
2023-08-28 17:59:12 +02:00
|
|
|
auto originalDefender = cb->getBattle(battleID)->battleGetUnitByID(unit->unitId());
|
2023-08-19 09:22:34 +02:00
|
|
|
|
|
|
|
auto dpsReduce = AttackPossibility::calculateDamageReduce(
|
|
|
|
nullptr,
|
2024-08-25 14:49:11 +02:00
|
|
|
originalDefender && originalDefender->alive() ? originalDefender : unit,
|
2023-08-19 09:22:34 +02:00
|
|
|
damage,
|
|
|
|
innerCache,
|
|
|
|
state);
|
|
|
|
|
|
|
|
auto ourUnit = unit->unitSide() == side ? 1 : -1;
|
|
|
|
auto goodEffect = newHealth > oldHealth ? 1 : -1;
|
|
|
|
|
|
|
|
if(ourUnit * goodEffect == 1)
|
|
|
|
{
|
2024-08-26 10:30:39 +02:00
|
|
|
auto isMagical = state->getForUpdate(unit->unitId())->summoned
|
|
|
|
|| unit->isClone()
|
|
|
|
|| unit->isGhost();
|
|
|
|
|
|
|
|
if(ourUnit && goodEffect && isMagical)
|
2023-08-19 09:22:34 +02:00
|
|
|
continue;
|
|
|
|
|
|
|
|
ps.value += dpsReduce * scoreEvaluator.getPositiveEffectMultiplier();
|
|
|
|
}
|
|
|
|
else
|
2024-08-26 10:30:39 +02:00
|
|
|
// discourage AI making collateral damage with spells
|
|
|
|
ps.value -= 4 * dpsReduce * scoreEvaluator.getNegativeEffectMultiplier();
|
2023-08-26 12:06:41 +02:00
|
|
|
|
|
|
|
#if BATTLE_TRACE_LEVEL >= 1
|
2024-09-11 16:05:53 +02:00
|
|
|
// Ensure ps.dest is not empty before accessing the first element
|
|
|
|
if (!ps.dest.empty())
|
|
|
|
{
|
|
|
|
logAi->trace(
|
|
|
|
"Spell %s to %d affects %s (%d), dps: %2f oldHealth: %d newHealth: %d",
|
|
|
|
ps.spell->getNameTranslated(),
|
|
|
|
ps.dest.at(0).hexValue.hex, // Safe to access .at(0) now
|
|
|
|
unit->creatureId().toCreature()->getNameSingularTranslated(),
|
|
|
|
unit->getCount(),
|
|
|
|
dpsReduce,
|
|
|
|
oldHealth,
|
|
|
|
newHealth);
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
// Handle the case where ps.dest is empty
|
|
|
|
logAi->trace(
|
|
|
|
"Spell %s has no destination, affects %s (%d), dps: %2f oldHealth: %d newHealth: %d",
|
|
|
|
ps.spell->getNameTranslated(),
|
|
|
|
unit->creatureId().toCreature()->getNameSingularTranslated(),
|
|
|
|
unit->getCount(),
|
|
|
|
dpsReduce,
|
|
|
|
oldHealth,
|
|
|
|
newHealth);
|
|
|
|
}
|
2023-08-26 12:06:41 +02:00
|
|
|
#endif
|
2023-08-19 09:22:34 +02:00
|
|
|
}
|
|
|
|
}
|
2024-08-25 14:49:11 +02:00
|
|
|
|
2023-08-26 12:06:41 +02:00
|
|
|
#if BATTLE_TRACE_LEVEL >= 1
|
|
|
|
logAi->trace("Total score: %2f", ps.value);
|
|
|
|
#endif
|
2023-08-19 09:22:34 +02:00
|
|
|
}
|
2023-08-26 12:06:41 +02:00
|
|
|
#if BATTLE_TRACE_LEVEL == 0
|
2023-08-19 09:22:34 +02:00
|
|
|
});
|
2023-08-26 12:06:41 +02:00
|
|
|
#endif
|
2023-08-19 09:22:34 +02:00
|
|
|
|
|
|
|
LOGFL("Evaluation took %d ms", timer.getDiff());
|
|
|
|
|
2024-08-25 14:49:11 +02:00
|
|
|
auto castToPerform = *vstd::maxElementByFun(possibleCasts, [](const PossibleSpellcast & ps) -> float
|
|
|
|
{
|
|
|
|
return ps.value;
|
|
|
|
});
|
2023-08-19 09:22:34 +02:00
|
|
|
|
2024-08-25 14:49:11 +02:00
|
|
|
if(castToPerform.value > cachedAttack.score && !vstd::isAlmostEqual(castToPerform.value, cachedAttack.score))
|
2023-08-19 09:22:34 +02:00
|
|
|
{
|
|
|
|
LOGFL("Best spell is %s (value %d). Will cast.", castToPerform.spell->getNameTranslated() % castToPerform.value);
|
|
|
|
BattleAction spellcast;
|
|
|
|
spellcast.actionType = EActionType::HERO_SPELL;
|
|
|
|
spellcast.spell = castToPerform.spell->id;
|
|
|
|
spellcast.setTarget(castToPerform.dest);
|
|
|
|
spellcast.side = side;
|
2024-08-11 22:22:35 +02:00
|
|
|
spellcast.stackNumber = -1;
|
2023-08-28 17:59:12 +02:00
|
|
|
cb->battleMakeSpellAction(battleID, spellcast);
|
2023-08-19 09:22:34 +02:00
|
|
|
activeActionMade = true;
|
|
|
|
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
LOGFL("Best spell is %s. But it is actually useless (value %d).", castToPerform.spell->getNameTranslated() % castToPerform.value);
|
|
|
|
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
//Below method works only for offensive spells
|
|
|
|
void BattleEvaluator::evaluateCreatureSpellcast(const CStack * stack, PossibleSpellcast & ps)
|
|
|
|
{
|
|
|
|
using ValueMap = PossibleSpellcast::ValueMap;
|
|
|
|
|
|
|
|
RNGStub rngStub;
|
2023-08-28 17:59:12 +02:00
|
|
|
HypotheticBattle state(env.get(), cb->getBattle(battleID));
|
|
|
|
TStacks all = cb->getBattle(battleID)->battleGetAllStacks(false);
|
2023-08-19 09:22:34 +02:00
|
|
|
|
|
|
|
ValueMap healthOfStack;
|
|
|
|
ValueMap newHealthOfStack;
|
|
|
|
|
|
|
|
for(auto unit : all)
|
|
|
|
{
|
|
|
|
healthOfStack[unit->unitId()] = unit->getAvailableHealth();
|
|
|
|
}
|
|
|
|
|
|
|
|
spells::BattleCast cast(&state, stack, spells::Mode::CREATURE_ACTIVE, ps.spell);
|
|
|
|
cast.castEval(state.getServerCallback(), ps.dest);
|
|
|
|
|
|
|
|
for(auto unit : all)
|
|
|
|
{
|
|
|
|
auto unitId = unit->unitId();
|
|
|
|
auto localUnit = state.battleGetUnitByID(unitId);
|
|
|
|
newHealthOfStack[unitId] = localUnit->getAvailableHealth();
|
|
|
|
}
|
|
|
|
|
|
|
|
int64_t totalGain = 0;
|
|
|
|
|
|
|
|
for(auto unit : all)
|
|
|
|
{
|
|
|
|
auto unitId = unit->unitId();
|
|
|
|
auto localUnit = state.battleGetUnitByID(unitId);
|
|
|
|
|
|
|
|
auto healthDiff = newHealthOfStack[unitId] - healthOfStack[unitId];
|
|
|
|
|
2023-08-28 17:59:12 +02:00
|
|
|
if(localUnit->unitOwner() != cb->getBattle(battleID)->getPlayerID())
|
2023-08-19 09:22:34 +02:00
|
|
|
healthDiff = -healthDiff;
|
|
|
|
|
|
|
|
if(healthDiff < 0)
|
|
|
|
{
|
|
|
|
ps.value = -1;
|
|
|
|
return; //do not damage own units at all
|
|
|
|
}
|
|
|
|
|
|
|
|
totalGain += healthDiff;
|
|
|
|
}
|
|
|
|
|
|
|
|
ps.value = totalGain;
|
|
|
|
}
|
|
|
|
|
|
|
|
void BattleEvaluator::print(const std::string & text) const
|
|
|
|
{
|
2023-09-04 21:21:02 +02:00
|
|
|
logAi->trace("%s Battle AI[%p]: %s", playerID.toString(), this, text);
|
2023-08-19 09:22:34 +02:00
|
|
|
}
|