File: GatherArmyBehavior.cpp

package info (click to toggle)
vcmi 1.6.5%2Bdfsg-2
  • links: PTS, VCS
  • area: contrib
  • in suites: forky, sid, trixie
  • size: 32,060 kB
  • sloc: cpp: 238,971; python: 265; sh: 224; xml: 157; ansic: 78; objc: 61; makefile: 49
file content (366 lines) | stat: -rw-r--r-- 9,063 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
/*
* GatherArmyBehavior.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 "../AIGateway.h"
#include "../Engine/Nullkiller.h"
#include "../Goals/ExecuteHeroChain.h"
#include "../Goals/Composition.h"
#include "../Goals/RecruitHero.h"
#include "../Markers/HeroExchange.h"
#include "../Markers/ArmyUpgrade.h"
#include "GatherArmyBehavior.h"
#include "CaptureObjectsBehavior.h"
#include "../AIUtility.h"
#include "../Goals/ExchangeSwapTownHeroes.h"

namespace NKAI
{

using namespace Goals;

std::string GatherArmyBehavior::toString() const
{
	return "Gather army";
}

Goals::TGoalVec GatherArmyBehavior::decompose(const Nullkiller * ai) const
{
	Goals::TGoalVec tasks;

	auto heroes = ai->cb->getHeroesInfo();

	if(heroes.empty())
	{
		return tasks;
	}

	for(const CGHeroInstance * hero : heroes)
	{
		if(ai->heroManager->getHeroRole(hero) == HeroRole::MAIN)
		{
			vstd::concatenate(tasks, deliverArmyToHero(ai, hero));
		}
	}

	auto towns = ai->cb->getTownsInfo();

	for(const CGTownInstance * town : towns)
	{
		vstd::concatenate(tasks, upgradeArmy(ai, town));
	}

	return tasks;
}

Goals::TGoalVec GatherArmyBehavior::deliverArmyToHero(const Nullkiller * ai, const CGHeroInstance * hero) const
{
	Goals::TGoalVec tasks;
	const int3 pos = hero->visitablePos();
	auto targetHeroScore = ai->heroManager->evaluateHero(hero);

#if NKAI_TRACE_LEVEL >= 1
	logAi->trace("Checking ways to gaher army for hero %s, %s", hero->getObjectName(), pos.toString());
#endif

	auto paths = ai->pathfinder->getPathInfo(pos, ai->isObjectGraphAllowed());

#if NKAI_TRACE_LEVEL >= 1
	logAi->trace("Gather army found %d paths", paths.size());
#endif

	for(const AIPath & path : paths)
	{
#if NKAI_TRACE_LEVEL >= 2
		logAi->trace("Path found %s, %s, %lld", path.toString(), path.targetHero->getObjectName(), path.heroArmy->getArmyStrength());
#endif
		
		if (path.targetHero->getOwner() != ai->playerID)
			continue;
		
		if(path.containsHero(hero))
		{
#if NKAI_TRACE_LEVEL >= 2
			logAi->trace("Selfcontaining path. Ignore");
#endif
			continue;
		}

		if(ai->arePathHeroesLocked(path))
		{
#if NKAI_TRACE_LEVEL >= 2
			logAi->trace("Ignore path because of locked hero");
#endif
			continue;
		}

		HeroExchange heroExchange(hero, path);

		uint64_t armyValue = heroExchange.getReinforcementArmyStrength(ai);
		float armyRatio = (float)armyValue / hero->getArmyStrength();

		// avoid transferring very small amount of army
		if((armyRatio < 0.1f && armyValue < 20000) || armyValue < 500)
		{
#if NKAI_TRACE_LEVEL >= 2
			logAi->trace("Army value is too small.");
#endif
			continue;
		}

		// avoid trying to move bigger army to the weaker one.
		bool hasOtherMainInPath = false;

		for(auto node : path.nodes)
		{
			if(!node.targetHero) continue;

			auto heroRole = ai->heroManager->getHeroRole(node.targetHero);

			if(heroRole == HeroRole::MAIN)
			{
				auto score = ai->heroManager->evaluateHero(node.targetHero);

				if(score >= targetHeroScore)
				{
					hasOtherMainInPath = true;

					break;
				}
			}
		}

		if(hasOtherMainInPath)
		{
#if NKAI_TRACE_LEVEL >= 2
			logAi->trace("Army value is too large.");
#endif
			continue;
		}

		auto danger = path.getTotalDanger();
		auto isSafe = isSafeToVisit(hero, path.heroArmy, danger, ai->settings->getSafeAttackRatio());

#if NKAI_TRACE_LEVEL >= 2
		logAi->trace(
			"It is %s to visit %s by %s with army %lld, danger %lld and army loss %lld",
			isSafe ? "safe" : "not safe",
			hero->getObjectName(),
			path.targetHero->getObjectName(),
			path.getHeroStrength(),
			danger,
			path.getTotalArmyLoss());
#endif

		if(isSafe)
		{
			Composition composition;
			ExecuteHeroChain exchangePath(path, hero);

			exchangePath.closestWayRatio = 1;

			composition.addNext(heroExchange);

			if(hero->inTownGarrison && path.turn() == 0)
			{
				auto lockReason = ai->getHeroLockedReason(hero);

				if(path.targetHero->visitedTown == hero->visitedTown)
				{
					composition.addNextSequence({
						sptr(ExchangeSwapTownHeroes(hero->visitedTown, hero, lockReason))});
				}
				else
				{
					composition.addNextSequence({
						sptr(ExchangeSwapTownHeroes(hero->visitedTown)),
						sptr(exchangePath),
						sptr(ExchangeSwapTownHeroes(hero->visitedTown, hero, lockReason))});
				}
			}
			else
			{
				composition.addNext(exchangePath);
			}

			auto blockedAction = path.getFirstBlockedAction();

			if(blockedAction)
			{
	#if NKAI_TRACE_LEVEL >= 2
				logAi->trace("Action is blocked. Considering decomposition.");
	#endif
				auto subGoal = blockedAction->decompose(ai, path.targetHero);

				if(subGoal->invalid())
				{
#if NKAI_TRACE_LEVEL >= 1
					logAi->trace("Path is invalid. Skipping");
#endif
					continue;
				}

				composition.addNext(subGoal);
			}
			
			tasks.push_back(sptr(composition));
		}
	}

	return tasks;
}

Goals::TGoalVec GatherArmyBehavior::upgradeArmy(const Nullkiller * ai, const CGTownInstance * upgrader) const
{
	Goals::TGoalVec tasks;
	const int3 pos = upgrader->visitablePos();
	TResources availableResources = ai->getFreeResources();

#if NKAI_TRACE_LEVEL >= 1
	logAi->trace("Checking ways to upgrade army in town %s, %s", upgrader->getObjectName(), pos.toString());
#endif
	
	auto paths = ai->pathfinder->getPathInfo(pos, ai->isObjectGraphAllowed());
	auto goals = CaptureObjectsBehavior::getVisitGoals(paths, ai);

	std::vector<std::shared_ptr<ExecuteHeroChain>> waysToVisitObj;

#if NKAI_TRACE_LEVEL >= 1
	logAi->trace("Found %d paths", paths.size());
#endif

	bool hasMainAround = false;

	for(const AIPath & path : paths)
	{
		auto heroRole = ai->heroManager->getHeroRole(path.targetHero);

		if(heroRole == HeroRole::MAIN && path.turn() < ai->settings->getScoutHeroTurnDistanceLimit())
			hasMainAround = true;
	}

	for(int i = 0; i < paths.size(); i++)
	{
		auto & path = paths[i];
		auto visitGoal = goals[i];

#if NKAI_TRACE_LEVEL >= 2
		logAi->trace("Path found %s, %s, %lld", path.toString(), path.targetHero->getObjectName(), path.heroArmy->getArmyStrength());
#endif

		if(visitGoal->invalid())
		{
#if NKAI_TRACE_LEVEL >= 2
			logAi->trace("Ignore path. Not valid way.");
#endif
			continue;
		}

		if(upgrader->visitingHero && (upgrader->visitingHero.get() != path.targetHero || path.exchangeCount == 1))
		{
#if NKAI_TRACE_LEVEL >= 2
			logAi->trace("Ignore path. Town has visiting hero.");
#endif
			continue;
		}

		if(ai->arePathHeroesLocked(path))
		{
#if NKAI_TRACE_LEVEL >= 2
			logAi->trace("Ignore path because of locked hero");
#endif
			continue;
		}

		if(path.getFirstBlockedAction())
		{
#if NKAI_TRACE_LEVEL >= 2
			// TODO: decomposition?
			logAi->trace("Ignore path. Action is blocked.");
#endif
			continue;
		}

		auto upgrade = ai->armyManager->calculateCreaturesUpgrade(path.heroArmy, upgrader, availableResources);

		if(!upgrader->garrisonHero
			&& (
				hasMainAround
				|| ai->heroManager->getHeroRole(path.targetHero) == HeroRole::MAIN))
		{
			ArmyUpgradeInfo armyToGetOrBuy;

			armyToGetOrBuy.addArmyToGet(
				ai->armyManager->getBestArmy(
					path.targetHero,
					path.heroArmy,
					upgrader->getUpperArmy()));

			armyToGetOrBuy.upgradeValue -= path.heroArmy->getArmyStrength();

			upgrade.upgradeValue += armyToGetOrBuy.upgradeValue;
			upgrade.upgradeCost += armyToGetOrBuy.upgradeCost;
			vstd::concatenate(upgrade.resultingArmy, armyToGetOrBuy.resultingArmy);

			if(!upgrade.upgradeValue
				&& armyToGetOrBuy.upgradeValue > 20000
				&& ai->heroManager->canRecruitHero(upgrader)
				&& path.turn() < ai->settings->getScoutHeroTurnDistanceLimit())
			{
				for(auto hero : cb->getAvailableHeroes(upgrader))
				{
					auto scoutReinforcement = ai->armyManager->howManyReinforcementsCanGet(hero, upgrader);

					if(scoutReinforcement >= armyToGetOrBuy.upgradeValue
						&& ai->getFreeGold() >20000
						&& !ai->buildAnalyzer->isGoldPressureHigh())
					{
						Composition recruitHero;

						recruitHero.addNext(ArmyUpgrade(path.targetHero, town, armyToGetOrBuy)).addNext(RecruitHero(upgrader, hero));
					}
				}
			}
		}

		auto armyValue = (float)upgrade.upgradeValue / path.getHeroStrength();

		if((armyValue < 0.25f && upgrade.upgradeValue < 40000) || upgrade.upgradeValue < 2000) // avoid small upgrades
		{
#if NKAI_TRACE_LEVEL >= 2
			logAi->trace("Ignore path. Army value is too small (%f)", armyValue);
#endif
			continue;
		}

		auto danger = path.getTotalDanger();

		auto isSafe = isSafeToVisit(path.targetHero, path.heroArmy, danger, ai->settings->getSafeAttackRatio());

#if NKAI_TRACE_LEVEL >= 2
		logAi->trace(
			"It is %s to visit %s by %s with army %lld, danger %lld and army loss %lld",
			isSafe ? "safe" : "not safe",
			upgrader->getObjectName(),
			path.targetHero->getObjectName(),
			path.getHeroStrength(),
			danger,
			path.getTotalArmyLoss());
#endif

		if(isSafe)
		{
			tasks.push_back(sptr(Composition().addNext(ArmyUpgrade(path, upgrader, upgrade)).addNext(visitGoal)));
		}
	}

	return tasks;
}

}