1
0
mirror of https://github.com/vcmi/vcmi.git synced 2025-11-25 22:42:04 +02:00
Files
vcmi/AI/Nullkiller2/Engine/Nullkiller.cpp

748 lines
20 KiB
C++
Raw Normal View History

/*
* Nullkiller.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 "Nullkiller.h"
#include <boost/range/algorithm/sort.hpp>
2021-05-16 15:39:38 +03:00
#include "../AIGateway.h"
#include "../Behaviors/CaptureObjectsBehavior.h"
#include "../Behaviors/RecruitHeroBehavior.h"
#include "../Behaviors/BuyArmyBehavior.h"
2021-05-16 13:53:32 +03:00
#include "../Behaviors/DefenceBehavior.h"
#include "../Behaviors/BuildingBehavior.h"
2021-05-16 14:19:07 +03:00
#include "../Behaviors/GatherArmyBehavior.h"
2021-05-16 14:45:12 +03:00
#include "../Behaviors/ClusterBehavior.h"
2023-09-24 13:07:42 +03:00
#include "../Behaviors/StayAtTownBehavior.h"
2024-05-19 10:04:45 +03:00
#include "../Behaviors/ExplorationBehavior.h"
#include "../Goals/Invalid.h"
2024-05-19 10:04:45 +03:00
#include "../../../lib/CPlayerState.h"
#include "../../lib/StartInfo.h"
#include "../../lib/pathfinder/PathfinderCache.h"
#include "../../lib/pathfinder/PathfinderOptions.h"
2025-08-13 17:16:27 +02:00
namespace NK2AI
2022-09-26 21:01:07 +03:00
{
using namespace Goals;
// while we play vcmieagles graph can be shared
std::unique_ptr<ObjectGraph> Nullkiller::baseGraph;
Nullkiller::Nullkiller()
: activeHero(nullptr)
, scanDepth(ScanDepth::MAIN_FULL)
, useHeroChain(true)
, memory(std::make_unique<AIMemory>())
{
2024-05-19 10:04:45 +03:00
}
Nullkiller::~Nullkiller() = default;
bool canUseOpenMap(const std::shared_ptr<CCallback>& cb, const PlayerColor playerID)
2024-05-19 10:04:45 +03:00
{
if(!cb->getStartInfo()->extraOptionsInfo.cheatsAllowed)
{
return false;
}
const TeamState * team = cb->getPlayerTeam(playerID);
const auto hasHumanInTeam = vstd::contains_if(
team->players,
[cb](const PlayerColor teamMateID) -> bool
2024-05-19 10:04:45 +03:00
{
return cb->getPlayerState(teamMateID)->isHuman();
}
);
2024-05-19 10:04:45 +03:00
return !hasHumanInTeam;
}
void Nullkiller::init(const std::shared_ptr<CCallback> & cbInput, AIGateway * aiGwInput)
{
cc = cbInput;
aiGw = aiGwInput;
playerID = aiGwInput->playerID;
settings = std::make_unique<Settings>(cc->getStartInfo()->difficulty);
PathfinderOptions pathfinderOptions(*cc);
pathfinderOptions.useTeleportTwoWay = true;
pathfinderOptions.useTeleportOneWay = settings->isOneWayMonolithUsageAllowed();
pathfinderOptions.useTeleportOneWayRandom = settings->isOneWayMonolithUsageAllowed();
pathfinderCache = std::make_unique<PathfinderCache>(cc.get(), pathfinderOptions);
if(canUseOpenMap(cc, playerID))
{
useObjectGraph = settings->isObjectGraphAllowed();
openMap = settings->isOpenMap() || useObjectGraph;
}
else
2024-05-19 10:04:45 +03:00
{
useObjectGraph = false;
openMap = false;
}
2024-02-03 12:20:59 +02:00
baseGraph.reset();
priorityEvaluator.reset(new PriorityEvaluator(this));
priorityEvaluators.reset(
new SharedPool<PriorityEvaluator>(
[&]()->std::unique_ptr<PriorityEvaluator>
{
2022-12-07 23:36:20 +02:00
return std::make_unique<PriorityEvaluator>(this);
}));
dangerHitMap.reset(new DangerHitMapAnalyzer(this));
2021-05-16 14:57:33 +03:00
buildAnalyzer.reset(new BuildAnalyzer(this));
objectClusterizer.reset(new ObjectClusterizer(this));
dangerEvaluator.reset(new FuzzyHelper(this));
pathfinder.reset(new AIPathfinder(cc.get(), this));
armyManager.reset(new ArmyManager(cc.get(), this));
heroManager.reset(new HeroManager(cc.get(), this));
2024-03-31 18:39:00 +03:00
decomposer.reset(new DeepDecomposer(this));
armyFormation.reset(new ArmyFormation(cc, this));
}
TaskPlanItem::TaskPlanItem(const TSubgoal & task)
: affectedObjects(task->asTask()->getAffectedObjects())
, task(task)
{
}
Goals::TTaskVec TaskPlan::getTasks() const
{
Goals::TTaskVec result;
for(auto & item : tasks)
{
result.push_back(taskptr(*item.task));
}
2021-05-15 21:27:22 +03:00
vstd::removeDuplicates(result);
2021-05-16 14:57:33 +03:00
return result;
}
2021-05-16 14:38:53 +03:00
void TaskPlan::merge(const TSubgoal & task)
{
TGoalVec blockers;
if (task->asTask()->priority <= 0)
return;
for(auto & item : tasks)
{
for(auto objid : item.affectedObjects)
{
if(task == item.task || task->asTask()->isObjectAffected(objid) || (task->asTask()->getHero() != nullptr && task->asTask()->getHero() == item.task->asTask()->getHero()))
{
if(item.task->asTask()->priority >= task->asTask()->priority)
return;
blockers.push_back(item.task);
break;
}
}
}
vstd::erase_if(tasks, [&](const TaskPlanItem & task2)
{
return vstd::contains(blockers, task2.task);
});
tasks.emplace_back(task);
}
Goals::TTask Nullkiller::choseBestTask(Goals::TGoalVec & tasks) const
{
2021-05-16 14:38:53 +03:00
if(tasks.empty())
{
return taskptr(Invalid());
}
for(const TSubgoal & task : tasks)
{
if(task->asTask()->priority <= 0)
task->asTask()->priority = priorityEvaluator->evaluate(task);
}
2021-05-16 14:38:53 +03:00
auto bestTask = *vstd::maxElementByFun(tasks, [](const Goals::TSubgoal& task) -> float
{
return task->asTask()->priority;
});
return taskptr(*bestTask);
}
Goals::TTaskVec Nullkiller::buildPlan(TGoalVec & tasks, int priorityTier) const
{
TaskPlan taskPlan;
tbb::parallel_for(tbb::blocked_range<size_t>(0, tasks.size()), [this, &tasks, priorityTier](const tbb::blocked_range<size_t> & r)
{
SET_GLOBAL_STATE_TBB(this->aiGw);
auto evaluator = this->priorityEvaluators->acquire();
for(size_t i = r.begin(); i != r.end(); i++)
{
const auto & task = tasks[i];
if(task->asTask()->priority <= 0 || priorityTier != PriorityEvaluator::PriorityTier::BUILDINGS)
task->asTask()->priority = evaluator->evaluate(task, priorityTier);
}
});
boost::range::sort(tasks, [](const TSubgoal& g1, const TSubgoal& g2) -> bool
{
return g2->asTask()->priority < g1->asTask()->priority;
});
for(const TSubgoal & task : tasks)
{
taskPlan.merge(task);
2021-05-16 14:38:53 +03:00
}
return taskPlan.getTasks();
}
void Nullkiller::decompose(Goals::TGoalVec & results, const Goals::TSubgoal& behavior, int decompositionMaxDepth) const
{
makingTurnInterruption.interruptionPoint();
logAi->debug("Decomposing behavior %s", behavior->toString());
const auto start = std::chrono::high_resolution_clock::now();
decomposer->decompose(results, behavior, decompositionMaxDepth);
makingTurnInterruption.interruptionPoint();
logAi->debug("Decomposing behavior %s done in %ld", behavior->toString(), timeElapsed(start));
}
2025-08-14 03:29:55 +02:00
void Nullkiller::resetState()
{
std::unique_lock lockGuard(aiStateMutex);
2023-12-17 10:11:05 +02:00
2021-05-16 15:39:38 +03:00
lockedResources = TResources();
2023-07-27 15:58:49 +03:00
scanDepth = ScanDepth::MAIN_FULL;
lockedHeroes.clear();
dangerHitMap->resetHitmap();
2022-09-06 21:14:22 +03:00
useHeroChain = true;
objectClusterizer->reset();
2024-05-19 10:04:45 +03:00
if(!baseGraph && isObjectGraphAllowed())
{
baseGraph = std::make_unique<ObjectGraph>();
baseGraph->updateGraph(this);
}
}
void Nullkiller::invalidatePathfinderData()
{
pathfinderInvalidated = true;
}
void Nullkiller::updateState()
{
#if NK2AI_TRACE_LEVEL >= 1
logAi->info("PERFORMANCE: AI updateState started");
#endif
makingTurnInterruption.interruptionPoint();
std::unique_lock lockGuard(aiStateMutex);
const auto start = std::chrono::high_resolution_clock::now();
activeHero = nullptr;
2023-02-28 09:07:59 +02:00
setTargetObject(-1);
decomposer->reset();
buildAnalyzer->update();
if(!pathfinderInvalidated && dangerHitMap->isHitMapUpToDate() && dangerHitMap->isTileOwnersUpToDate())
logAi->trace("Skipping full state regeneration - up to date");
else
2022-09-06 21:14:22 +03:00
{
memory->removeInvisibleObjects(cc.get());
2022-09-06 21:14:22 +03:00
dangerHitMap->updateHitMap();
dangerHitMap->calculateTileOwners();
makingTurnInterruption.interruptionPoint();
2022-09-06 21:14:22 +03:00
heroManager->update();
logAi->trace("Updating paths");
2022-09-06 21:14:22 +03:00
PathfinderSettings cfg;
cfg.useHeroChain = useHeroChain;
cfg.allowBypassObjects = true;
2024-05-19 10:04:45 +03:00
if(scanDepth == ScanDepth::SMALL || isObjectGraphAllowed())
2022-09-06 21:14:22 +03:00
{
2024-03-08 14:39:16 +02:00
cfg.mainTurnDistanceLimit = settings->getMainHeroTurnDistanceLimit();
2023-07-27 15:58:49 +03:00
}
2024-05-19 10:04:45 +03:00
if(scanDepth != ScanDepth::ALL_FULL || isObjectGraphAllowed())
2023-07-27 15:58:49 +03:00
{
cfg.scoutTurnDistanceLimit = settings->getScoutHeroTurnDistanceLimit();
2022-09-06 21:14:22 +03:00
}
2021-05-16 15:01:34 +03:00
makingTurnInterruption.interruptionPoint();
const auto heroes = getHeroesForPathfinding();
pathfinder->updatePaths(heroes, cfg);
2024-03-08 14:39:16 +02:00
2024-05-19 10:04:45 +03:00
if(isObjectGraphAllowed())
2024-03-08 14:39:16 +02:00
{
2024-03-29 20:39:03 +02:00
pathfinder->updateGraphs(
heroes,
scanDepth == ScanDepth::SMALL ? PathfinderSettings::MaxTurnDistanceLimit : 10,
scanDepth == ScanDepth::ALL_FULL ? PathfinderSettings::MaxTurnDistanceLimit : 3);
2024-03-08 14:39:16 +02:00
}
makingTurnInterruption.interruptionPoint();
2022-09-06 21:14:22 +03:00
objectClusterizer->clusterize();
pathfinderInvalidated = false;
2022-09-06 21:14:22 +03:00
}
2022-09-06 21:14:22 +03:00
armyManager->update();
#if NK2AI_TRACE_LEVEL >= 1
if(const auto timeElapsedMs = timeElapsed(start); timeElapsedMs > 499)
{
logAi->warn("PERFORMANCE: AI updateState took %ld ms", timeElapsedMs);
}
else
{
logAi->info("PERFORMANCE: AI updateState took %ld ms", timeElapsedMs);
}
#endif
}
bool Nullkiller::isHeroLocked(const CGHeroInstance * hero) const
{
return getHeroLockedReason(hero) != HeroLockedReason::NOT_LOCKED;
}
bool Nullkiller::arePathHeroesLocked(const AIPath & path) const
{
if(getHeroLockedReason(path.targetHero) == HeroLockedReason::STARTUP)
{
2025-08-24 21:15:34 +02:00
#if NK2AI_TRACE_LEVEL >= 1
2023-02-28 09:07:59 +02:00
logAi->trace("Hero %s is locked by STARTUP. Discarding %s", path.targetHero->getObjectName(), path.toString());
#endif
return true;
}
for(const auto & node : path.nodes)
{
auto lockReason = getHeroLockedReason(node.targetHero);
if(lockReason != HeroLockedReason::NOT_LOCKED)
{
2025-08-24 21:15:34 +02:00
#if NK2AI_TRACE_LEVEL >= 1
logAi->trace("Hero %s is locked by %d. Discarding %s", path.targetHero->getObjectName(), (int)lockReason, path.toString());
#endif
return true;
}
}
return false;
}
HeroLockedReason Nullkiller::getHeroLockedReason(const CGHeroInstance * hero) const
{
auto found = lockedHeroes.find(hero);
return found != lockedHeroes.end() ? found->second : HeroLockedReason::NOT_LOCKED;
}
void Nullkiller::makeTurn()
{
2025-02-28 15:28:38 +01:00
std::lock_guard<std::mutex> sharedStorageLock(AISharedStorage::locker);
const int MAX_DEPTH = 10;
2025-08-14 03:29:55 +02:00
resetState();
Goals::TGoalVec tasks;
tracePlayerStatus(true);
2025-08-14 03:29:55 +02:00
for(int i = 1; i <= settings->getMaxPass() && cc->getPlayerStatus(playerID) == EPlayerStatus::INGAME; i++)
{
if (!updateStateAndExecutePriorityPass(tasks, i)) return;
2022-09-06 21:14:22 +03:00
tasks.clear();
decompose(tasks, sptr(CaptureObjectsBehavior()), 1);
decompose(tasks, sptr(ClusterBehavior()), MAX_DEPTH);
decompose(tasks, sptr(DefenceBehavior()), MAX_DEPTH);
decompose(tasks, sptr(GatherArmyBehavior()), MAX_DEPTH);
decompose(tasks, sptr(StayAtTownBehavior()), MAX_DEPTH);
2024-05-19 10:04:45 +03:00
if(!isOpenMap())
decompose(tasks, sptr(ExplorationBehavior()), MAX_DEPTH);
2024-05-19 10:04:45 +03:00
TTaskVec selectedTasks;
2025-08-24 21:15:34 +02:00
#if NK2AI_TRACE_LEVEL >= 1
int prioOfTask = 0;
2025-08-19 19:29:28 +02:00
#endif
for (int prio = PriorityEvaluator::PriorityTier::INSTAKILL; prio <= PriorityEvaluator::PriorityTier::MAX_PRIORITY_TIER; ++prio)
{
2025-08-24 21:15:34 +02:00
#if NK2AI_TRACE_LEVEL >= 1
prioOfTask = prio;
2025-08-19 19:29:28 +02:00
#endif
selectedTasks = buildPlan(tasks, prio);
if (!selectedTasks.empty() || settings->isUseFuzzy())
break;
}
2022-09-06 21:14:22 +03:00
boost::range::sort(selectedTasks, [](const TTask& a, const TTask& b)
{
return a->priority > b->priority;
});
if(selectedTasks.empty())
{
2024-06-01 09:08:23 +03:00
selectedTasks.push_back(taskptr(Goals::Invalid()));
}
2022-09-06 21:14:22 +03:00
bool hasAnySuccess = false;
2025-08-14 03:29:55 +02:00
for(const auto& selectedTask : selectedTasks)
2021-05-16 15:01:34 +03:00
{
if(cc->getPlayerStatus(playerID) != EPlayerStatus::INGAME)
2024-04-20 10:33:37 +03:00
return;
2025-08-14 03:29:55 +02:00
if(!areAffectedObjectsPresent(selectedTask))
2024-04-27 10:57:30 +03:00
{
logAi->debug("Affected object not found. Canceling task.");
continue;
}
2025-08-14 03:29:55 +02:00
std::string taskDescription = selectedTask->toString();
HeroRole heroRole = getTaskRole(selectedTask);
2025-08-14 03:29:55 +02:00
if(heroRole != HeroRole::MAIN || selectedTask->getHeroExchangeCount() <= 1)
useHeroChain = false;
2024-03-29 20:39:03 +02:00
// TODO: better to check turn distance here instead of priority
2025-08-14 03:29:55 +02:00
if((heroRole != HeroRole::MAIN || selectedTask->priority < SMALL_SCAN_MIN_PRIORITY)
&& scanDepth == ScanDepth::MAIN_FULL)
2023-07-27 15:58:49 +03:00
{
useHeroChain = false;
scanDepth = ScanDepth::SMALL;
2024-03-29 20:39:03 +02:00
logAi->trace(
"Goal %s has low priority %f so decreasing scan depth to gain performance.",
2024-03-29 20:39:03 +02:00
taskDescription,
2025-08-14 03:29:55 +02:00
selectedTask->priority);
}
2025-08-14 03:29:55 +02:00
if((settings->isUseFuzzy() && selectedTask->priority < MIN_PRIORITY) || (!settings->isUseFuzzy() && selectedTask->priority <= 0))
{
auto heroes = cc->getHeroesInfo();
const auto hasMp = vstd::contains_if(heroes, [](const CGHeroInstance * h) -> bool
{
return h->movementPointsRemaining() > 100;
});
if(hasMp && scanDepth != ScanDepth::ALL_FULL)
{
logAi->trace(
"Goal %s has too low priority %f so increasing scan depth to full.",
taskDescription,
2025-08-14 03:29:55 +02:00
selectedTask->priority);
scanDepth = ScanDepth::ALL_FULL;
useHeroChain = false;
hasAnySuccess = true;
break;
}
logAi->trace("Goal %s has too low priority. It is not worth doing it.", taskDescription);
2024-03-29 20:39:03 +02:00
continue;
2023-07-27 15:58:49 +03:00
}
2025-08-14 03:29:55 +02:00
logAi->info("Pass %d: Performing prio %d task %s with prio: %d", i, prioOfTask, selectedTask->toString(), selectedTask->priority);
if(HeroPtr heroPtr(selectedTask->getHero(), cc); selectedTask->getHero() && !heroPtr.isVerified(false))
{
logAi->warn("Nullkiller::makeTurn Skipping pass due to unverified hero: %s", heroPtr.nameOrDefault());
}
else
{
if(!executeTask(selectedTask))
{
if(hasAnySuccess)
break;
return;
}
hasAnySuccess = true;
}
}
hasAnySuccess |= handleTrading();
if(!hasAnySuccess)
{
logAi->trace("Nothing was done this turn. Ending turn.");
tracePlayerStatus(false);
return;
}
2023-08-05 13:49:49 +03:00
for (const auto *heroInfo : cc->getHeroesInfo())
AIGateway::pickBestArtifacts(cc, heroInfo);
Per-hero artifact scoring for NKAI AI now has better (but not perfect) system for scoring artifacts. All artifacts now have their base score, based on bonuses provided by the artifact. For composite artifacts, AI will also consider bonuses from its components. When exploring, AI will now weight artifacts as min(base score, price / 5), meaning even artifacts that AI can't score will still have some priority, if only to sell them or deny them to enemy AI will now also consider what to equip when trading with heroes or on the end of AI pass. When considering what to equip, hero will use base score of an artifact, adjusted by how relevant particular bonus / artifact for a hero. Some examples: - Morale-bonusing artifacts have their score reduced based on percentage of undeads in the army, all the way to 0 for undead-only troops - Artifacts that give spells (books, hat) will have score reduced based on how many of these spells are already known by hero - Land movement artifacts have zero score while on water and vice versa - Necromancy artifacts will have zero score if hero does not have necromancy - Archery artifacts are scaled by amount of ranged troops, and only used if hero has archery skill AI may still equip 'bad' artifact, however this should only happen if hero has no other artifacts to equip into said slot. TODO's for future PR's (although not sure if / when I will work on these): - avoid equipping duplicates of the same artifact. Most notably with scrolls, but may happen with other misc artifacts or rings. - consideration for various spell-immunity neclaces - consideration for birectional artifacts, like Shackles of War, or some Spheres - since these artifacts need consideration on what our expected enemy is to correctly estimate whether - equipping artifacts based on immediate need - for example, equipping recovery artifacts before end of day, equipping legion pieces only in town on day 7, preparing for strong / weak enemies (or even preparing for specific enemy in advance) - transferring resource-generating artifacts and such to scout heroes, allowing main hero to focus on combat - ensure that AI can equip combined artifacts even if non-primary slots are in use - by considering whether score of combined artifact is higher than score of all used slots
2025-01-18 13:14:24 +00:00
2024-02-25 12:39:19 +02:00
if(i == settings->getMaxPass())
2023-08-05 13:49:49 +03:00
{
logAi->warn("MaxPass reached. Terminating AI turn.");
}
}
}
bool Nullkiller::updateStateAndExecutePriorityPass(Goals::TGoalVec & tempResults, const int passIndex)
{
updateState();
Goals::TTask bestPrioPassTask = taskptr(Goals::Invalid());
for(int i = 1; i <= settings->getMaxPriorityPass() && cc->getPlayerStatus(playerID) == EPlayerStatus::INGAME; i++)
{
tempResults.clear();
decompose(tempResults, sptr(RecruitHeroBehavior()), 1);
decompose(tempResults, sptr(BuyArmyBehavior()), 1);
decompose(tempResults, sptr(BuildingBehavior()), 1);
bestPrioPassTask = choseBestTask(tempResults);
if(bestPrioPassTask->priority > 0)
{
logAi->info("Pass %d: Performing priorityPass %d task %s with prio: %d", passIndex, i, bestPrioPassTask->toString(), bestPrioPassTask->priority);
if(HeroPtr heroPtr(bestPrioPassTask->getHero(), cc); bestPrioPassTask->getHero() && !heroPtr.isVerified(false))
{
logAi->warn("Nullkiller::updateStateAndExecutePriorityPass Skipping priorityPass due to unverified hero: %s", heroPtr.nameOrDefault());
}
else if(!executeTask(bestPrioPassTask))
{
logAi->warn("Task failed to execute");
return false;
}
updateState();
}
else
{
break;
}
if(i == settings->getMaxPriorityPass())
{
logAi->warn("MaxPriorityPass reached. Terminating priorityPass loop.");
2023-08-05 13:49:49 +03:00
}
2022-09-06 21:14:22 +03:00
}
return true;
2022-09-06 21:14:22 +03:00
}
2021-05-16 15:08:39 +03:00
bool Nullkiller::areAffectedObjectsPresent(const Goals::TTask & task) const
2024-04-27 10:57:30 +03:00
{
auto affectedObjs = task->getAffectedObjects();
for(auto oid : affectedObjs)
{
if(!cc->getObj(oid, false))
2024-04-27 10:57:30 +03:00
return false;
}
return true;
}
HeroRole Nullkiller::getTaskRole(const Goals::TTask & task) const
2024-04-27 10:57:30 +03:00
{
HeroPtr heroPtr(task->getHero(), cc);
2024-04-27 10:57:30 +03:00
HeroRole heroRole = HeroRole::MAIN;
if(heroPtr.isVerified())
heroRole = heroManager->getHeroRoleOrDefault(heroPtr);
2024-04-27 10:57:30 +03:00
return heroRole;
}
bool Nullkiller::executeTask(const Goals::TTask & task) const
2022-09-06 21:14:22 +03:00
{
auto start = std::chrono::high_resolution_clock::now();
2022-09-06 21:14:22 +03:00
std::string taskDescr = task->toString();
makingTurnInterruption.interruptionPoint();
2022-09-06 21:14:22 +03:00
logAi->debug("Trying to realize %s (value %2.3f)", taskDescr, task->priority);
2022-09-06 21:14:22 +03:00
try
{
task->accept(aiGw);
logAi->trace("Task %s completed in %lld", taskDescr, timeElapsed(start));
2022-09-06 21:14:22 +03:00
}
catch(goalFulfilledException &)
{
logAi->trace("Task %s completed in %lld", taskDescr, timeElapsed(start));
2022-09-06 21:14:22 +03:00
}
2022-11-03 21:16:49 +02:00
catch(cannotFulfillGoalException & e)
2022-09-06 21:14:22 +03:00
{
2023-02-28 09:07:59 +02:00
logAi->error("Failed to realize subgoal of type %s, I will stop.", taskDescr);
logAi->error("The error message was: %s", e.what());
return false;
}
return true;
2021-05-16 15:39:38 +03:00
}
TResources Nullkiller::getFreeResources() const
2021-05-16 15:39:38 +03:00
{
auto freeRes = cc->getResourceAmount() - lockedResources;
2021-05-16 15:39:38 +03:00
freeRes.positive();
return freeRes;
}
void Nullkiller::lockResources(const TResources & res)
2021-05-16 15:39:38 +03:00
{
lockedResources += res;
2021-11-23 09:41:03 +03:00
}
2022-09-26 21:01:07 +03:00
bool Nullkiller::handleTrading()
{
bool haveTraded = false;
bool shouldTryToTrade = true;
ObjectInstanceID marketId;
for (const auto town : cc->getTownsInfo())
{
if (town->hasBuiltSomeTradeBuilding())
{
marketId = town->id;
}
}
if (!marketId.hasValue())
return false;
if (const CGObjectInstance* obj = cc->getObj(marketId, false))
{
if (const auto* m = dynamic_cast<const IMarket*>(obj))
{
while (shouldTryToTrade)
{
shouldTryToTrade = false;
buildAnalyzer->update();
TResources required = buildAnalyzer->getTotalResourcesRequired();
TResources income = buildAnalyzer->getDailyIncome();
TResources available = cc->getResourceAmount();
2025-08-24 21:15:34 +02:00
#if NK2AI_TRACE_LEVEL >= 2
logAi->debug("Available %s", available.toString());
logAi->debug("Required %s", required.toString());
#endif
int mostWanted = -1;
int mostExpendable = -1;
float minRatio = std::numeric_limits<float>::max();
float maxRatio = std::numeric_limits<float>::min();
for (int i = 0; i < required.size(); ++i)
{
if (required[i] <= 0)
continue;
float ratio = static_cast<float>(available[i]) / required[i];
if (ratio < minRatio) {
minRatio = ratio;
mostWanted = i;
}
}
for (int i = 0; i < required.size(); ++i)
{
float ratio;
if (required[i] > 0)
ratio = static_cast<float>(available[i]) / required[i];
else
ratio = available[i];
bool okToSell = false;
if (i == GameResID::GOLD)
{
if (income[i] > 0 && !buildAnalyzer->isGoldPressureOverMax())
okToSell = true;
}
else
{
if (required[i] <= 0 && income[i] > 0)
okToSell = true;
}
if (ratio > maxRatio && okToSell) {
maxRatio = ratio;
mostExpendable = i;
}
}
2025-08-24 21:15:34 +02:00
#if NK2AI_TRACE_LEVEL >= 2
logAi->debug("mostExpendable: %d mostWanted: %d", mostExpendable, mostWanted);
#endif
if (mostExpendable == mostWanted || mostWanted == -1 || mostExpendable == -1)
return false;
int toGive;
int toGet;
m->getOffer(mostExpendable, mostWanted, toGive, toGet, EMarketMode::RESOURCE_RESOURCE);
//logAi->info("Offer is: I get %d of %s for %d of %s at %s", toGet, mostWanted, toGive, mostExpendable, obj->getObjectName());
//TODO trade only as much as needed
if (toGive && toGive <= available[mostExpendable]) //don't try to sell 0 resources
{
cc->trade(m->getObjInstanceID(), EMarketMode::RESOURCE_RESOURCE, GameResID(mostExpendable), GameResID(mostWanted), toGive);
2025-08-24 21:15:34 +02:00
#if NK2AI_TRACE_LEVEL >= 2
logAi->info("Traded %d of %s for %d of %s at %s", toGive, mostExpendable, toGet, mostWanted, obj->getObjectName());
#endif
haveTraded = true;
shouldTryToTrade = true;
}
}
}
}
return haveTraded;
}
std::shared_ptr<const CPathsInfo> Nullkiller::getPathsInfo(const CGHeroInstance * h) const
{
return pathfinderCache->getPathsInfo(h);
}
void Nullkiller::invalidatePaths()
{
pathfinderCache->invalidatePaths();
}
void Nullkiller::tracePlayerStatus(bool beginning) const
{
2025-08-24 21:15:34 +02:00
#if NK2AI_TRACE_LEVEL >= 1
float totalHeroesStrength = 0;
int totalTownsLevel = 0;
for (const auto *heroInfo : cc->getHeroesInfo())
{
totalHeroesStrength += heroInfo->getTotalStrength();
}
for (const auto *townInfo : cc->getTownsInfo())
{
totalTownsLevel += townInfo->getTownLevel();
}
const auto *firstWord = beginning ? "Beginning:" : "End:";
logAi->info("%s totalHeroesStrength: %f, totalTownsLevel: %d, resources: %s", firstWord, totalHeroesStrength, totalTownsLevel, cc->getResourceAmount().toString());
#endif
}
std::map<const CGHeroInstance *, HeroRole> Nullkiller::getHeroesForPathfinding() const
{
std::map<const CGHeroInstance *, HeroRole> activeHeroes;
for(auto hero : cc->getHeroesInfo())
{
if(getHeroLockedReason(hero) == HeroLockedReason::DEFENCE)
continue;
activeHeroes[hero] = heroManager->getHeroRoleOrDefaultInefficient(hero);
}
return activeHeroes;
}
2022-09-26 21:01:07 +03:00
}