From 601ced3749607b5186e01b1f439c62ca28bd8151 Mon Sep 17 00:00:00 2001 From: Andrii Danylchenko Date: Mon, 11 Apr 2022 09:12:41 +0300 Subject: [PATCH] BattleAI: rework movement when no targtes --- AI/BattleAI/AttackPossibility.cpp | 29 +-- AI/BattleAI/AttackPossibility.h | 8 + AI/BattleAI/BattleAI.cpp | 110 +++++------ AI/BattleAI/BattleExchangeVariant.cpp | 264 +++++++++++++++++++++----- AI/BattleAI/BattleExchangeVariant.h | 53 +++--- AI/BattleAI/PotentialTargets.cpp | 10 +- AI/BattleAI/PotentialTargets.h | 2 +- AI/Nullkiller/AIGateway.cpp | 7 +- lib/battle/ReachabilityInfo.cpp | 7 +- 9 files changed, 347 insertions(+), 143 deletions(-) diff --git a/AI/BattleAI/AttackPossibility.cpp b/AI/BattleAI/AttackPossibility.cpp index f73c2996c..c1f5d67a6 100644 --- a/AI/BattleAI/AttackPossibility.cpp +++ b/AI/BattleAI/AttackPossibility.cpp @@ -28,6 +28,22 @@ int64_t AttackPossibility::attackValue() const return damageDiff(); } +int64_t AttackPossibility::calculateDpsReduce( + const battle::Unit * attacker, + const battle::Unit * defender, + uint64_t damageDealt, + std::shared_ptr cb) +{ + vstd::amin(damageDealt, defender->getAvailableHealth()); + + auto enemyDamageBeforeAttack = cb->battleEstimateDamage(BattleAttackInfo(defender, attacker, defender->canShoot())); + auto enemiesKilled = damageDealt / defender->MaxHealth() + (damageDealt % defender->MaxHealth() >= defender->getFirstHPleft() ? 1 : 0); + auto enemyDps = (enemyDamageBeforeAttack.first + enemyDamageBeforeAttack.second) / 2; + auto dpsPerEnemy = enemyDps / (double)defender->getCount(); + + return (int64_t)(dpsPerEnemy * (enemiesKilled + damageDealt / (double)defender->MaxHealth()) / 2); +} + int64_t AttackPossibility::evaluateBlockedShootersDmg(const BattleAttackInfo & attackInfo, BattleHex hex, const HypotheticBattle * state) { int64_t res = 0; @@ -136,15 +152,9 @@ AttackPossibility AttackPossibility::evaluate(const BattleAttackInfo & attackInf vstd::amin(retaliation.second, ap.attackerState->getAvailableHealth()); damageDealt = (attackDmg.first + attackDmg.second) / 2; + enemyDpsReduce = calculateDpsReduce(attacker, defender, damageDealt, getCbc()); ap.attackerState->afterAttack(attackInfo.shooting, false); - auto enemiesKilled = damageDealt / u->MaxHealth() + (damageDealt % u->MaxHealth() >= u->getFirstHPleft() ? 1 : 0); - auto enemyDps = (enemyDamageBeforeAttack.first + enemyDamageBeforeAttack.second) / 2; - - enemyDpsReduce = enemiesKilled - ? (int64_t)(enemyDps * enemiesKilled / (double)u->getCount()) - : (int64_t)(enemyDps / (double)u->getCount() * damageDealt / u->getFirstHPleft()); - //FIXME: use ranged retaliation damageReceived = 0; ourDpsReduce = 0; @@ -152,11 +162,8 @@ AttackPossibility AttackPossibility::evaluate(const BattleAttackInfo & attackInf if (!attackInfo.shooting && defenderState->ableToRetaliate() && !counterAttacksBlocked) { damageReceived = (retaliation.first + retaliation.second) / 2; + ourDpsReduce = calculateDpsReduce(defender, attacker, damageReceived, getCbc()); defenderState->afterAttack(attackInfo.shooting, true); - - auto ourUnitsKilled = damageReceived / attacker->MaxHealth() + (damageReceived % attacker->MaxHealth() >= attacker->getFirstHPleft() ? 1 : 0); - - ourDpsReduce = (int64_t)(damageDealt * ourUnitsKilled / (double)attacker->getCount()); } bool isEnemy = state->battleMatchOwner(attacker, u); diff --git a/AI/BattleAI/AttackPossibility.h b/AI/BattleAI/AttackPossibility.h index 669ea205b..758e7fe7e 100644 --- a/AI/BattleAI/AttackPossibility.h +++ b/AI/BattleAI/AttackPossibility.h @@ -13,6 +13,8 @@ #include "common.h" #include "StackWithBonuses.h" +#define BATTLE_TRACE_LEVEL 0 + class AttackPossibility { public: @@ -36,6 +38,12 @@ public: static AttackPossibility evaluate(const BattleAttackInfo & attackInfo, BattleHex hex, const HypotheticBattle * state); + static int64_t calculateDpsReduce( + const battle::Unit * attacker, + const battle::Unit * defender, + uint64_t damageDealt, + std::shared_ptr cb); + private: static int64_t evaluateBlockedShootersDmg(const BattleAttackInfo & attackInfo, BattleHex hex, const HypotheticBattle * state); }; diff --git a/AI/BattleAI/BattleAI.cpp b/AI/BattleAI/BattleAI.cpp index 07297fc67..67ebc3e71 100644 --- a/AI/BattleAI/BattleAI.cpp +++ b/AI/BattleAI/BattleAI.cpp @@ -94,7 +94,10 @@ void CBattleAI::init(std::shared_ptr ENV, std::shared_ptrnodeName()); + + BattleAction result = BattleAction::makeDefend(stack); setCbc(cb); //TODO: make solid sure that AIs always use their callbacks (need to take care of event handlers too) + try { if(stack->type->idNumber == CreatureID::CATAPULT) @@ -162,84 +165,83 @@ BattleAction CBattleAI::activeStack( const CStack * stack ) PotentialTargets targets(stack, &hb); BattleExchangeEvaluator scoreEvaluator(cb, env); + auto moveTarget = scoreEvaluator.findMoveTowardsUnreachable(stack, targets, hb); + + int64_t score = EvaluationResult::INEFFECTIVE_SCORE; if(!targets.possibleAttacks.empty()) { +#if BATTLE_TRACE_LEVEL==1 logAi->trace("Evaluating attack for %s", stack->getDescription()); +#endif auto evaluationResult = scoreEvaluator.findBestTarget(stack, targets, hb); auto & bestAttack = evaluationResult.bestAttack; - + //TODO: consider more complex spellcast evaluation, f.e. because "re-retaliation" during enemy move in same turn for melee attack etc. if(bestSpellcast.is_initialized() && bestSpellcast->value > bestAttack.damageDiff()) + { + // return because spellcast value is damage dealt and score is dps reduce return BattleAction::makeCreatureSpellcast(stack, bestSpellcast->dest, bestSpellcast->spell->id); - - if(evaluationResult.wait) - { - return BattleAction::makeWait(stack); } - if(evaluationResult.score == EvaluationResult::INEFFECTIVE_SCORE) + if(evaluationResult.score > score) { - return BattleAction::makeDefend(stack); - } - - if(bestAttack.attack.shooting) - { - auto &target = bestAttack; - logAi->debug("BattleAI: %s -> %s x %d, shot, from %d curpos %d dist %d speed %d: %lld %lld %lld", - target.attackerState->unitType()->identifier, - target.affectedUnits[0]->unitType()->identifier, - (int)target.affectedUnits.size(), (int)target.from, (int)bestAttack.attack.attacker->getPosition().hex, + auto & target = bestAttack; + score = evaluationResult.score; + std::string action; + + if(evaluationResult.wait) + { + result = BattleAction::makeWait(stack); + action = "wait"; + } + else if(bestAttack.attack.shooting) + { + + result = BattleAction::makeShotAttack(stack, bestAttack.attack.defender); + action = "shot"; + } + else + { + result = BattleAction::makeMeleeAttack(stack, bestAttack.attack.defender->getPosition(), bestAttack.from); + action = "mellee"; + } + + logAi->debug("BattleAI: %s -> %s x %d, %s, from %d curpos %d dist %d speed %d: %lld %lld %lld", + bestAttack.attackerState->unitType()->identifier, + bestAttack.affectedUnits[0]->unitType()->identifier, + (int)bestAttack.affectedUnits[0]->getCount(), action, (int)bestAttack.from, (int)bestAttack.attack.attacker->getPosition().hex, bestAttack.attack.chargedFields, bestAttack.attack.attacker->Speed(0, true), - target.damageDealt, target.damageReceived, target.attackValue() + bestAttack.damageDealt, bestAttack.damageReceived, bestAttack.attackValue() ); - - return BattleAction::makeShotAttack(stack, bestAttack.attack.defender); } - else - { - auto &target = bestAttack; - logAi->debug("BattleAI: %s -> %s x %d, mellee, from %d curpos %d dist %d speed %d: %lld %lld %lld", - target.attackerState->unitType()->identifier, - target.affectedUnits[0]->unitType()->identifier, - (int)target.affectedUnits.size(), (int)target.from, (int)bestAttack.attack.attacker->getPosition().hex, - bestAttack.attack.chargedFields, bestAttack.attack.attacker->Speed(0, true), - target.damageDealt, target.damageReceived, target.attackValue() - ); - - return BattleAction::makeMeleeAttack(stack, bestAttack.attack.defender->getPosition(), bestAttack.from); - } } else if(bestSpellcast.is_initialized()) { return BattleAction::makeCreatureSpellcast(stack, bestSpellcast->dest, bestSpellcast->spell->id); } - else + + //ThreatMap threatsToUs(stack); // These lines may be usefull but they are't used in the code. + if(moveTarget.score > score) { + score = moveTarget.score; + if(stack->waited()) { - //ThreatMap threatsToUs(stack); // These lines may be usefull but they are't used in the code. - auto dists = cb->getReachability(stack); - if(!targets.unreachableEnemies.empty()) - { - auto closestEnemy = vstd::minElementByFun(targets.unreachableEnemies, [&](const battle::Unit * enemy) -> int - { - return dists.distToNearestNeighbour(stack, enemy); - }); - - if(dists.distToNearestNeighbour(stack, *closestEnemy) < GameConstants::BFIELD_SIZE) - { - return goTowardsNearest(stack, (*closestEnemy)->getAttackableHexes(stack)); - } - } + result = goTowardsNearest(stack, moveTarget.positions); } else { - return BattleAction::makeWait(stack); + result = BattleAction::makeWait(stack); } } + if(score > EvaluationResult::INEFFECTIVE_SCORE) + { + return result; + } + if(!stack->hasBonusOfType(Bonus::FLYING) && stack->unitSide() == BattleSide::ATTACKER && cb->battleGetSiegeLevel() >= CGTownInstance::CITADEL) @@ -252,7 +254,7 @@ BattleAction CBattleAI::activeStack( const CStack * stack ) return BattleAction::makeMove(stack, stack->getPosition().cloneInDirection(BattleHex::RIGHT)); else return goTowardsNearest(stack, brokenWallMoat); - } + } } } catch(boost::thread_interrupted &) @@ -264,7 +266,7 @@ BattleAction CBattleAI::activeStack( const CStack * stack ) logAi->error("Exception occurred in %s %s",__FUNCTION__, e.what()); } - return BattleAction::makeDefend(stack); + return result; } BattleAction CBattleAI::goTowardsNearest(const CStack * stack, std::vector hexes) const @@ -289,10 +291,10 @@ BattleAction CBattleAI::goTowardsNearest(const CStack * stack, std::vectorcoversPos(hex)) { - logAi->warn("Warning: already standing on neighbouring tile!"); - //We shouldn't even be here... - return BattleAction::makeDefend(stack); - } + logAi->warn("Warning: already standing on neighbouring tile!"); + //We shouldn't even be here... + return BattleAction::makeDefend(stack); + } } BattleHex bestNeighbor = hexes.front(); diff --git a/AI/BattleAI/BattleExchangeVariant.cpp b/AI/BattleAI/BattleExchangeVariant.cpp index 519469e60..2667efad6 100644 --- a/AI/BattleAI/BattleExchangeVariant.cpp +++ b/AI/BattleAI/BattleExchangeVariant.cpp @@ -11,6 +11,18 @@ #include "BattleExchangeVariant.h" #include "../../lib/CStack.h" +AttackerValue::AttackerValue() +{ + value = 0; + isRetalitated = false; +} + +MoveTarget::MoveTarget() + :positions() +{ + score = EvaluationResult::INEFFECTIVE_SCORE; +} + int64_t BattleExchangeVariant::trackAttack(const AttackPossibility & ap, HypotheticBattle * state) { auto affectedUnits = ap.affectedUnits; @@ -31,6 +43,7 @@ int64_t BattleExchangeVariant::trackAttack(const AttackPossibility & ap, Hypothe dpsScore += attackValue; +#if BATTLE_TRACE_LEVEL==1 logAi->trace( "%s -> %s, ap attack, %s, dps: %d, score: %d", ap.attack.attacker->getDescription(), @@ -38,6 +51,7 @@ int64_t BattleExchangeVariant::trackAttack(const AttackPossibility & ap, Hypothe ap.attack.shooting ? "shot" : "mellee", ap.damageDealt, attackValue); +#endif return attackValue; } @@ -56,13 +70,20 @@ int64_t BattleExchangeVariant::trackAttack( TDmgRange retalitation; BattleAttackInfo bai(attacker.get(), defender.get(), shooting); + + if(shooting) + { + bai.attackerPos.setXY(8, 5); + } + auto attack = cb->battleEstimateDamage(bai, &retalitation); int64_t attackDamage = (attack.first + attack.second) / 2; - int64_t defenderDpsReduce = calculateDpsReduce(attacker.get(), defender.get(), attackDamage, cb); + int64_t defenderDpsReduce = AttackPossibility::calculateDpsReduce(attacker.get(), defender.get(), attackDamage, cb); int64_t attackerDpsReduce = 0; if(!evaluateOnly) { +#if BATTLE_TRACE_LEVEL==1 logAi->trace( "%s -> %s, normal attack, %s, dps: %d, %d", attacker->getDescription(), @@ -70,6 +91,7 @@ int64_t BattleExchangeVariant::trackAttack( shooting ? "shot" : "mellee", attackDamage, defenderDpsReduce); +#endif if(isOurAttack) { @@ -88,16 +110,18 @@ int64_t BattleExchangeVariant::trackAttack( if(retalitation.second != 0) { auto retalitationDamage = (retalitation.first + retalitation.second) / 2; - attackerDpsReduce = calculateDpsReduce(defender.get(), attacker.get(), retalitationDamage, cb); + attackerDpsReduce = AttackPossibility::calculateDpsReduce(defender.get(), attacker.get(), retalitationDamage, cb); if(!evaluateOnly) { +#if BATTLE_TRACE_LEVEL==1 logAi->trace( "%s -> %s, retalitation, dps: %d, %d", defender->getDescription(), attacker->getDescription(), retalitationDamage, attackerDpsReduce); +#endif if(isOurAttack) { @@ -118,30 +142,16 @@ int64_t BattleExchangeVariant::trackAttack( auto score = defenderDpsReduce - attackerDpsReduce; +#if BATTLE_TRACE_LEVEL==1 if(!score) { logAi->trace("Zero %d %d", defenderDpsReduce, attackerDpsReduce); } +#endif return score; } -int64_t BattleExchangeVariant::calculateDpsReduce( - const battle::Unit * attacker, - const battle::Unit * defender, - uint64_t damageDealt, - std::shared_ptr cb) const -{ - vstd::amin(damageDealt, defender->getAvailableHealth()); - - auto enemyDamageBeforeAttack = cb->battleEstimateDamage(BattleAttackInfo(defender, attacker, defender->canShoot())); - auto enemiesKilled = damageDealt / defender->MaxHealth() + (damageDealt % defender->MaxHealth() >= defender->getFirstHPleft() ? 1 : 0); - auto enemyDps = (enemyDamageBeforeAttack.first + enemyDamageBeforeAttack.second) / 2; - - return (int64_t)(enemyDps * enemiesKilled / (double)defender->getCount() - + enemyDps / (double)defender->getCount() * ((damageDealt - defender->getFirstHPleft()) % defender->MaxHealth()) / defender->MaxHealth()); -}; - EvaluationResult BattleExchangeEvaluator::findBestTarget(const battle::Unit * activeStack, PotentialTargets & targets, HypotheticBattle & hb) { EvaluationResult result(targets.bestAction()); @@ -150,7 +160,7 @@ EvaluationResult BattleExchangeEvaluator::findBestTarget(const battle::Unit * ac for(auto & ap : targets.possibleAttacks) { - int64_t score = calculateExchange(ap); + int64_t score = calculateExchange(ap, targets, hb); if(score > result.score) { @@ -161,7 +171,9 @@ EvaluationResult BattleExchangeEvaluator::findBestTarget(const battle::Unit * ac if(!activeStack->waited()) { +#if BATTLE_TRACE_LEVEL==1 logAi->trace("Evaluating waited attack for %s", activeStack->getDescription()); +#endif hb.getForUpdate(activeStack->unitId())->waiting = true; hb.getForUpdate(activeStack->unitId())->waitedThisTurn = true; @@ -170,7 +182,7 @@ EvaluationResult BattleExchangeEvaluator::findBestTarget(const battle::Unit * ac for(auto & ap : targets.possibleAttacks) { - int64_t score = calculateExchange(ap); + int64_t score = calculateExchange(ap, targets, hb); if(score > result.score) { @@ -184,8 +196,94 @@ EvaluationResult BattleExchangeEvaluator::findBestTarget(const battle::Unit * ac return result; } +MoveTarget BattleExchangeEvaluator::findMoveTowardsUnreachable(const battle::Unit * activeStack, PotentialTargets & targets, HypotheticBattle & hb) +{ + MoveTarget result; + BattleExchangeVariant ev; + + if(targets.unreachableEnemies.empty()) + return result; + + updateReachabilityMap(hb); + + auto dists = cb->getReachability(activeStack); + auto speed = activeStack->Speed(); + + for(const battle::Unit * enemy : targets.unreachableEnemies) + { + int64_t stackScore = EvaluationResult::INEFFECTIVE_SCORE; + + std::vector adjacentStacks = getAdjacentUnits(enemy); + auto closestStack = *vstd::minElementByFun(adjacentStacks, [&](const battle::Unit * u) -> int64_t + { + return dists.distToNearestNeighbour(activeStack, u) * 100000 - activeStack->getTotalHealth(); + }); + + auto distance = dists.distToNearestNeighbour(activeStack, closestStack); + + if(distance >= GameConstants::BFIELD_SIZE) + continue; + + if(distance <= speed) + continue; + + auto turnsToRich = (distance - 1) / speed + 1; + auto hexes = closestStack->getSurroundingHexes(); + + for(auto hex : hexes) + { + auto bai = BattleAttackInfo(activeStack, closestStack, cb->battleCanShoot(activeStack)); + auto attack = AttackPossibility::evaluate(bai, hex, &hb); + + attack.shootersBlockedDmg = 0; // we do not want to count on it, it is not for sure + + auto score = calculateExchange(attack, targets, hb) / turnsToRich; + + if(result.score < score) + { + result.score = score; + result.positions = closestStack->getAttackableHexes(activeStack); + } + } + } + + return result; +} + +std::vector BattleExchangeEvaluator::getAdjacentUnits(const battle::Unit * blockerUnit) +{ + std::queue queue; + std::vector checkedStacks; + + queue.push(blockerUnit); + + while(!queue.empty()) + { + auto stack = queue.front(); + + queue.pop(); + checkedStacks.push_back(stack); + + auto hexes = stack->getSurroundingHexes(); + for(auto hex : hexes) + { + auto neighbor = cb->battleGetStackByPos(hex); + + if(neighbor && neighbor->unitSide() == stack->unitSide() && !vstd::contains(checkedStacks, neighbor)) + { + queue.push(neighbor); + checkedStacks.push_back(neighbor); + } + } + } + + return checkedStacks; +} + std::vector BattleExchangeEvaluator::getExchangeUnits( - const AttackPossibility & ap) + const AttackPossibility & ap, + PotentialTargets & targets, + HypotheticBattle & hb) { auto hexes = ap.attack.defender->getHexes(); @@ -201,9 +299,33 @@ std::vector BattleExchangeEvaluator::getExchangeUnits( vstd::removeDuplicates(allReachableUnits); + auto copy = allReachableUnits; + for(auto unit : copy) + { + for(auto adjacentUnit : getAdjacentUnits(unit)) + { + auto unitWithBonuses = hb.battleGetUnitByID(adjacentUnit->unitId()); + + if(vstd::contains(targets.unreachableEnemies, adjacentUnit) + && !vstd::contains(allReachableUnits, unitWithBonuses)) + { + allReachableUnits.push_back(unitWithBonuses); + } + } + } + + vstd::removeDuplicates(allReachableUnits); + + if(!vstd::contains(allReachableUnits, ap.attack.attacker)) + { + allReachableUnits.push_back(ap.attack.attacker); + } + if(allReachableUnits.size() < 2) { +#if BATTLE_TRACE_LEVEL==1 logAi->trace("Reachability map contains only %d stacks", allReachableUnits.size()); +#endif return exchangeUnits; } @@ -220,16 +342,21 @@ std::vector BattleExchangeEvaluator::getExchangeUnits( return exchangeUnits; } -int64_t BattleExchangeEvaluator::calculateExchange(const AttackPossibility & ap) +int64_t BattleExchangeEvaluator::calculateExchange( + const AttackPossibility & ap, + PotentialTargets & targets, + HypotheticBattle & hb) { +#if BATTLE_TRACE_LEVEL==1 logAi->trace("Battle exchange at %d", ap.attack.shooting ? ap.dest : ap.from); +#endif std::vector ourStacks; std::vector enemyStacks; enemyStacks.push_back(ap.attack.defender); - std::vector exchangeUnits = getExchangeUnits(ap); + std::vector exchangeUnits = getExchangeUnits(ap, targets, hb); if(exchangeUnits.empty()) { @@ -250,7 +377,6 @@ int64_t BattleExchangeEvaluator::calculateExchange(const AttackPossibility & ap) { bool isOur = cb->battleMatchOwner(ap.attack.attacker, unit, true); auto & attackerQueue = isOur ? ourStacks : enemyStacks; - auto & oppositeQueue = isOur ? enemyStacks : ourStacks; if(!vstd::contains(attackerQueue, unit)) { @@ -268,13 +394,11 @@ int64_t BattleExchangeEvaluator::calculateExchange(const AttackPossibility & ap) auto attacker = exchangeBattle.getForUpdate(activeUnit->unitId()); - if(!attacker->alive() || oppositeQueue.empty()) + if(!attacker->alive()) { - logAi->trace( - "Attacker [%s] dead(%d) or opposite queue empty(%d)", - attacker->getDescription(), - attacker->alive() ? 0 : 1, - oppositeQueue.size()); +#if BATTLE_TRACE_LEVEL==1 + logAi->trace( "Attacker is dead"); +#endif continue; } @@ -283,21 +407,54 @@ int64_t BattleExchangeEvaluator::calculateExchange(const AttackPossibility & ap) if(!isOur || !exchangeBattle.getForUpdate(targetUnit->unitId())->alive()) { - targetUnit = *vstd::maxElementByFun(oppositeQueue, [&](const battle::Unit * u) -> int64_t + auto estimateAttack = [&](const battle::Unit * u) -> int64_t + { + auto stackWithBonuses = exchangeBattle.getForUpdate(u->unitId()); + auto score = v.trackAttack( + attacker, + stackWithBonuses, + exchangeBattle.battleCanShoot(stackWithBonuses.get()), + isOur, + cb, + true); + +#if BATTLE_TRACE_LEVEL==1 + logAi->trace("Best target selector %s->%s score = %d", attacker->getDescription(), u->getDescription(), score); +#endif + + return score; + }; + + if(!oppositeQueue.empty()) + { + targetUnit = *vstd::maxElementByFun(oppositeQueue, estimateAttack); + } + else + { + auto reachable = exchangeBattle.battleGetUnitsIf([&](const battle::Unit * u) -> bool + { + if(!u->alive() || u->unitSide() == attacker->unitSide()) + return false; + + return vstd::contains_if(reachabilityMap[u->getPosition()], [&](const battle::Unit * other) -> bool + { + return attacker->unitId() == other->unitId(); + }); + }); + + if(!reachable.empty()) { - auto stackWithBonuses = exchangeBattle.getForUpdate(u->unitId()); - auto score = v.trackAttack( - attacker, - stackWithBonuses, - exchangeBattle.battleCanShoot(stackWithBonuses.get()), - isOur, - cb, - true); + targetUnit = *vstd::maxElementByFun(reachable, estimateAttack); + } + else + { +#if BATTLE_TRACE_LEVEL==1 + logAi->trace("Battle queue is empty and no reachable enemy."); +#endif - logAi->trace("Best target selector %s->%s score = %d", attacker->getDescription(), u->getDescription(), score); - - return score; - }); + continue; + } + } } auto defender = exchangeBattle.getForUpdate(targetUnit->unitId()); @@ -334,7 +491,9 @@ int64_t BattleExchangeEvaluator::calculateExchange(const AttackPossibility & ap) v.adjustPositions(melleeAttackers, ap, reachabilityMap); +#if BATTLE_TRACE_LEVEL==1 logAi->trace("Exchange score: %ld", v.getScore()); +#endif return v.getScore(); } @@ -419,6 +578,16 @@ void BattleExchangeEvaluator::updateReachabilityMap(HypotheticBattle & hb) for(const battle::Unit * unit : turnQueue) { + if(turnBattle.battleCanShoot(unit)) + { + for(BattleHex hex = BattleHex::TOP_LEFT; hex.isValid(); hex = hex + 1) + { + reachabilityMap[hex].push_back(unit); + } + + continue; + } + auto unitReachability = turnBattle.getReachability(unit); for(BattleHex hex = BattleHex::TOP_LEFT; hex.isValid(); hex = hex + 1) @@ -453,6 +622,8 @@ bool BattleExchangeEvaluator::checkPositionBlocksOurStacks(HypotheticBattle & hb { int blockingScore = 0; + auto activeUnitDamage = activeUnit->getMinDamage(hb.battleCanShoot(activeUnit)) * activeUnit->getCount(); + for(int turn = 0; turn < turnOrder.size(); turn++) { auto & turnQueue = turnOrder[turn]; @@ -466,6 +637,11 @@ bool BattleExchangeEvaluator::checkPositionBlocksOurStacks(HypotheticBattle & hb if(unit->unitId() == unitToUpdate->unitId() || cb->battleMatchOwner(unit, activeUnit, false)) continue; + auto blockedUnitDamage = unit->getMinDamage(hb.battleCanShoot(unit)) * unit->getCount(); + + if(blockedUnitDamage < activeUnitDamage) + continue; + auto unitReachability = turnBattle.getReachability(unit); for(BattleHex hex = BattleHex::TOP_LEFT; hex.isValid(); hex = hex + 1) @@ -498,7 +674,9 @@ bool BattleExchangeEvaluator::checkPositionBlocksOurStacks(HypotheticBattle & hb } } +#if BATTLE_TRACE_LEVEL==1 logAi->trace("Position %d, blocking score %d", position.hex, blockingScore); +#endif return blockingScore > 50; } diff --git a/AI/BattleAI/BattleExchangeVariant.h b/AI/BattleAI/BattleExchangeVariant.h index 81545e263..abb9eb4c2 100644 --- a/AI/BattleAI/BattleExchangeVariant.h +++ b/AI/BattleAI/BattleExchangeVariant.h @@ -20,10 +20,30 @@ struct AttackerValue bool isRetalitated; BattleHex position; - AttackerValue() + AttackerValue(); +}; + +struct MoveTarget +{ + int64_t score; + std::vector positions; + + MoveTarget(); +}; + +struct EvaluationResult +{ + static const int64_t INEFFECTIVE_SCORE = -1000000; + + AttackPossibility bestAttack; + MoveTarget bestMove; + bool wait; + int64_t score; + bool defend; + + EvaluationResult(const AttackPossibility & ap) + :wait(false), score(0), bestAttack(ap), defend(false) { - value = 0; - isRetalitated = false; } }; @@ -55,27 +75,6 @@ public: private: int64_t dpsScore; std::map attackerValue; - - int64_t calculateDpsReduce( - const battle::Unit * attacker, - const battle::Unit * defender, - uint64_t damageDealt, - std::shared_ptr cb) const; -}; - -struct EvaluationResult -{ - static const int64_t INEFFECTIVE_SCORE = -1000000; - - AttackPossibility bestAttack; - bool wait; - int64_t score; - bool defend; - - EvaluationResult(AttackPossibility & ap) - :wait(false), score(0), bestAttack(ap), defend(false) - { - } }; class BattleExchangeEvaluator @@ -93,8 +92,10 @@ public: } EvaluationResult findBestTarget(const battle::Unit * activeStack, PotentialTargets & targets, HypotheticBattle & hb); - int64_t calculateExchange(const AttackPossibility & ap); + int64_t calculateExchange(const AttackPossibility & ap, PotentialTargets & targets, HypotheticBattle & hb); void updateReachabilityMap(HypotheticBattle & hb); - std::vector getExchangeUnits(const AttackPossibility & ap); + std::vector getExchangeUnits(const AttackPossibility & ap, PotentialTargets & targets, HypotheticBattle & hb); bool checkPositionBlocksOurStacks(HypotheticBattle & hb, const battle::Unit * unit, BattleHex position); + MoveTarget findMoveTowardsUnreachable(const battle::Unit * activeStack, PotentialTargets & targets, HypotheticBattle & hb); + std::vector getAdjacentUnits(const battle::Unit * unit); }; \ No newline at end of file diff --git a/AI/BattleAI/PotentialTargets.cpp b/AI/BattleAI/PotentialTargets.cpp index 66a84e114..aa9f7d71e 100644 --- a/AI/BattleAI/PotentialTargets.cpp +++ b/AI/BattleAI/PotentialTargets.cpp @@ -13,9 +13,7 @@ PotentialTargets::PotentialTargets(const battle::Unit * attacker, const HypotheticBattle * state) { - auto attIter = state->stackStates.find(attacker->unitId()); - const battle::Unit * attackerInfo = (attIter == state->stackStates.end()) ? attacker : attIter->second.get(); - + auto attackerInfo = state->battleGetUnitByID(attacker->unitId()); auto reachability = state->getReachability(attackerInfo); auto avHexes = state->battleGetAvailableHexes(reachability, attackerInfo); @@ -95,7 +93,7 @@ PotentialTargets::PotentialTargets(const battle::Unit * attacker, const Hypothet if (!possibleAttacks.empty()) { - auto &bestAp = possibleAttacks[0]; + auto & bestAp = possibleAttacks[0]; logGlobal->info("Battle AI best: %s -> %s at %d from %d, affects %d units: %lld %lld %lld %lld", bestAp.attack.attacker->unitType()->identifier, @@ -112,10 +110,10 @@ int64_t PotentialTargets::bestActionValue() const return bestAction().attackValue(); } -AttackPossibility PotentialTargets::bestAction() const +const AttackPossibility & PotentialTargets::bestAction() const { if(possibleAttacks.empty()) throw std::runtime_error("No best action, since we don't have any actions"); - return possibleAttacks[0]; + return possibleAttacks.at(0); //return *vstd::maxElementByFun(possibleAttacks, [](const AttackPossibility &ap) { return ap.attackValue(); } ); } diff --git a/AI/BattleAI/PotentialTargets.h b/AI/BattleAI/PotentialTargets.h index 220cdaead..4fba5a332 100644 --- a/AI/BattleAI/PotentialTargets.h +++ b/AI/BattleAI/PotentialTargets.h @@ -19,6 +19,6 @@ public: PotentialTargets(){}; PotentialTargets(const battle::Unit * attacker, const HypotheticBattle * state); - AttackPossibility bestAction() const; + const AttackPossibility & bestAction() const; int64_t bestActionValue() const; }; diff --git a/AI/Nullkiller/AIGateway.cpp b/AI/Nullkiller/AIGateway.cpp index f22efda7c..6a6dfd299 100644 --- a/AI/Nullkiller/AIGateway.cpp +++ b/AI/Nullkiller/AIGateway.cpp @@ -27,7 +27,9 @@ namespace NKAI { +// our to enemy strength ratio constants const float SAFE_ATTACK_CONSTANT = 1.2; +const float RETREAT_THRESHOLD = 0.3; //one thread may be turn of AI and another will be handling a side effect for AI2 boost::thread_specific_ptr cb; @@ -202,6 +204,9 @@ void AIGateway::gameOver(PlayerColor player, const EVictoryLossCheckResult & vic logAi->debug("AIGateway: Player %d (%s) lost. It's me. What a disappointment! :(", player, player.getStr()); } + // some whitespace to flush stream + logAi->debug(std::string(200, ' ')); + finish(); } } @@ -498,7 +503,7 @@ boost::optional AIGateway::makeSurrenderRetreatDecision( double fightRatio = battleState.getOurStrength() / (double)battleState.getEnemyStrength(); // if we have no towns - things are already bad, so retreat is not an option. - if(cb->getTownsInfo().size() && fightRatio < 0.3 && battleState.canFlee) + if(cb->getTownsInfo().size() && fightRatio < RETREAT_THRESHOLD && battleState.canFlee) { return BattleAction::makeRetreat(battleState.ourSide); } diff --git a/lib/battle/ReachabilityInfo.cpp b/lib/battle/ReachabilityInfo.cpp index 0a5452e26..4e16fbe28 100644 --- a/lib/battle/ReachabilityInfo.cpp +++ b/lib/battle/ReachabilityInfo.cpp @@ -70,7 +70,12 @@ int ReachabilityInfo::distToNearestNeighbour( const battle::Unit * defender, BattleHex * chosenHex) const { - auto attackableHexes = defender->getAttackableHexes(attacker); + auto attackableHexes = defender->getHexes(); + + if(attacker->doubleWide()) + { + vstd::concatenate(attackableHexes, battle::Unit::getHexes(defender->occupiedHex(), true, attacker->unitSide())); + } return distToNearestNeighbour(attackableHexes, chosenHex); }