CGeniusAI.cpp 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386
  1. #include "CGeniusAI.h"
  2. #include <iostream>
  3. #include <boost/lexical_cast.hpp>
  4. #include "../../lib/CBuildingHandler.h"
  5. #include "../../lib/CHeroHandler.h"
  6. #include "../../lib/VCMI_Lib.h"
  7. #include "../../lib/NetPacks.h"
  8. #include "AIPriorities.h"
  9. using std::endl;
  10. using geniusai::CGeniusAI;
  11. class LibClasses;
  12. #if defined (_MSC_VER) && (_MSC_VER >= 1020) || (__MINGW32__)
  13. // Excludes rarely used stuff from windows headers - delete this line if
  14. // something is missing.
  15. #define WIN32_LEAN_AND_MEAN
  16. #include <windows.h>
  17. #endif
  18. void DbgBox(const char* msg, bool messageBox)
  19. {
  20. #if defined PRINT_DEBUG
  21. #if defined _DEBUG
  22. //# if 0
  23. # if defined (_MSC_VER) && (_MSC_VER >= 1020)
  24. if (messageBox)
  25. {
  26. MessageBoxA(NULL, msg, "Debug message", MB_OK | MB_ICONASTERISK);
  27. }
  28. # endif
  29. tlog6 << msg << std::endl;
  30. #endif
  31. #endif
  32. }
  33. // TODO: Rewrite those i-s, o-s to something meaningful.
  34. bool CGeniusAI::AIObjectContainer::operator<(const AIObjectContainer& b) const
  35. {
  36. if (o->pos != b.o->pos)
  37. return o->pos < b.o->pos;
  38. else
  39. return o->id < b.o->id;
  40. }
  41. CGeniusAI::HypotheticalGameState::HeroModel::HeroModel(
  42. const CGHeroInstance* h)
  43. : h(h), finished(false)
  44. {
  45. pos = h->getPosition(false);
  46. remainingMovement = h->movement;
  47. }
  48. CGeniusAI::HypotheticalGameState::TownModel::TownModel(
  49. const CGTownInstance* t)
  50. : t(t)
  51. {
  52. hasBuilt = static_cast<bool>(t->builded);
  53. creaturesToRecruit = t->creatures;
  54. //creaturesInGarrison = t->getArmy();
  55. }
  56. CGeniusAI::HypotheticalGameState::HypotheticalGameState(CGeniusAI& ai)
  57. : knownVisitableObjects(ai.knownVisitableObjects)
  58. {
  59. AI = &ai;
  60. std::vector<const CGHeroInstance*> heroes = ai.m_cb->getHeroesInfo();
  61. for (std::vector<const CGHeroInstance*>::iterator i = heroes.begin();
  62. i != heroes.end();
  63. i++)
  64. heroModels.push_back(HeroModel(*i));
  65. std::vector<const CGTownInstance*> towns = ai.m_cb->getTownsInfo();
  66. for (std::vector <const CGTownInstance*>::iterator i = towns.begin();
  67. i != towns.end();
  68. i++) {
  69. if ( (*i)->tempOwner == ai.m_cb->getMyColor() )
  70. townModels.push_back(TownModel(*i));
  71. }
  72. if (ai.m_cb->howManyTowns() != 0) {
  73. AvailableHeroesToBuy =
  74. ai.m_cb->getAvailableHeroes(ai.m_cb->getTownInfo(0,0));
  75. }
  76. for (int i = 0; i < 8; i++)
  77. resourceAmounts.push_back(ai.m_cb->getResourceAmount(i));
  78. }
  79. void CGeniusAI::HypotheticalGameState::update(CGeniusAI& ai)
  80. {
  81. AI = &ai;
  82. knownVisitableObjects = ai.knownVisitableObjects;
  83. std::vector<HeroModel> oldModels = heroModels;
  84. heroModels.clear();
  85. std::vector<const CGHeroInstance*> heroes = ai.m_cb->getHeroesInfo();
  86. for (std::vector<const CGHeroInstance*>::iterator i = heroes.begin(); i != heroes.end(); i++)
  87. heroModels.push_back(HeroModel(*i));
  88. int j;
  89. for (int i = 0; i < oldModels.size(); ++i)
  90. {
  91. for (j = 0; j < heroModels.size(); ++j)
  92. {
  93. if (oldModels[i].h->subID == heroModels[j].h->subID)
  94. {
  95. heroModels[j].finished = oldModels[i].finished;
  96. heroModels[j].previouslyVisited_pos = oldModels[i].previouslyVisited_pos;
  97. }
  98. }
  99. }
  100. townModels.clear();
  101. std::vector<const CGTownInstance*> towns = ai.m_cb->getTownsInfo();
  102. for (std::vector<const CGTownInstance*>::iterator i = towns.begin(); i != towns.end(); i++)
  103. {
  104. if ( (*i)->tempOwner == ai.m_cb->getMyColor() )
  105. townModels.push_back(TownModel(*i));
  106. }
  107. if (ai.m_cb->howManyTowns())
  108. {
  109. AvailableHeroesToBuy = ai.m_cb->getAvailableHeroes(ai.m_cb->getTownInfo(0,0));
  110. }
  111. resourceAmounts.clear();
  112. for (int i = 0; i < 8; i++)
  113. resourceAmounts.push_back(ai.m_cb->getResourceAmount(i));
  114. }
  115. CGeniusAI::HeroObjective::HeroObjective(const HypotheticalGameState &hgs,
  116. Type t,
  117. const CGObjectInstance* object,
  118. HypotheticalGameState::HeroModel* h,
  119. CGeniusAI* ai)
  120. : object(object), hgs(hgs)
  121. {
  122. AI = ai;
  123. pos = object->pos;
  124. type = t;
  125. whoCanAchieve.push_back(h);
  126. _value = -1;
  127. }
  128. float CGeniusAI::HeroObjective::getValue() const
  129. {
  130. if (_value >= 0)
  131. return _value - _cost;
  132. // TODO: each object should have an associated cost to visit IE
  133. // (tree of knowledge 1000 gold/10 gems)
  134. vector<int> resourceCosts;
  135. for (int i = 0; i < 8; i++)
  136. resourceCosts.push_back(0);
  137. if (object->ID == 47) // School of magic
  138. resourceCosts[6] += 1000;
  139. // TODO: Add some meaningful (and not exploitable) number here.
  140. float bestCost = 9e9f;
  141. HypotheticalGameState::HeroModel* bestHero = NULL;
  142. if (type != AIObjective::finishTurn)
  143. {
  144. for (int i = 0; i < whoCanAchieve.size(); i++)
  145. {
  146. int distOutOfTheWay = 0;
  147. CPath path3;
  148. //from hero to object
  149. if (AI->m_cb->getPath(whoCanAchieve[i]->pos,
  150. pos,
  151. whoCanAchieve[i]->h,
  152. path3)) {
  153. distOutOfTheWay+=path3.nodes[0].dist;
  154. }
  155. // from object to goal
  156. if (AI->m_cb->getPath(pos,
  157. whoCanAchieve[i]->interestingPos,
  158. whoCanAchieve[i]->h,
  159. path3)) {
  160. distOutOfTheWay += path3.nodes[0].dist;
  161. // from hero directly to goal
  162. if (AI->m_cb->getPath(whoCanAchieve[i]->pos,
  163. whoCanAchieve[i]->interestingPos,
  164. whoCanAchieve[i]->h,
  165. path3))
  166. distOutOfTheWay-=path3.nodes[0].dist;
  167. }
  168. float cost = AI->m_priorities->getCost(resourceCosts,
  169. whoCanAchieve[i]->h,
  170. distOutOfTheWay);
  171. if (cost < bestCost)
  172. {
  173. bestCost = cost;
  174. bestHero = whoCanAchieve[i];
  175. }
  176. } // for (int i = 0; i < whoCanAchieve.size(); i++)
  177. }
  178. else // if (type != AIObjective::finishTurn)
  179. bestCost = 0;
  180. if (bestHero)
  181. {
  182. whoCanAchieve.clear();
  183. whoCanAchieve.push_back(bestHero);
  184. }
  185. _value = AI->m_priorities->getValue(*this);
  186. _cost = bestCost;
  187. return _value - _cost;
  188. }
  189. bool CGeniusAI::HeroObjective::operator<(const HeroObjective& other) const
  190. {
  191. if (type != other.type)
  192. return type < other.type;
  193. else if (pos != other.pos)
  194. return pos < other.pos;
  195. else if (object->id != other.object->id)
  196. return object->id < other.object->id;
  197. else if ((dynamic_cast<const CGVisitableOPH*>(object) != NULL) &&
  198. (whoCanAchieve.front()->h->id != other.whoCanAchieve.front()->h->id))
  199. return whoCanAchieve.front()->h->id < other.whoCanAchieve.front()->h->id;
  200. else
  201. return false;
  202. }
  203. void CGeniusAI::HeroObjective::print() const
  204. {
  205. switch (type)
  206. {
  207. case visit:
  208. tlog6 << "visit " << object->hoverName
  209. << " at (" <<object->pos.x << ","<< object->pos.y << ")" ;
  210. break;
  211. case attack:
  212. tlog6 << "attack " << object->hoverName;
  213. break;
  214. case finishTurn:
  215. tlog6 << "finish turn";
  216. // TODO: Add a default, just in case.
  217. }
  218. if (whoCanAchieve.size() == 1)
  219. tlog6 << " with " << whoCanAchieve.front()->h->hoverName;
  220. }
  221. CGeniusAI::TownObjective::TownObjective(
  222. const HypotheticalGameState& hgs,
  223. Type t,
  224. HypotheticalGameState::TownModel* tn,
  225. int Which,
  226. CGeniusAI * ai)
  227. : whichTown(tn), which(Which), hgs(hgs)
  228. {
  229. AI = ai;
  230. type = t;
  231. _value = -1;
  232. }
  233. float CGeniusAI::TownObjective::getValue() const
  234. {
  235. if (_value >= 0)
  236. return _value - _cost;
  237. // TODO: Include a constant stating the meaning of 8 (number of resources).
  238. vector<int> resourceCosts(8,0);
  239. CBuilding* b = NULL;
  240. CCreature* creature = NULL;
  241. float cost = 0; // TODO: Needed?
  242. int ID = 0;
  243. int newID = 0;
  244. int howMany = 0;
  245. ui32 creatures_max = 0;
  246. switch (type)
  247. {
  248. case recruitHero:
  249. resourceCosts[6] = 2500; // TODO: Define somehow the meaning of gold etc.
  250. break;
  251. case buildBuilding:
  252. b = VLC->buildh->buildings[whichTown->t->subID][which];
  253. for (int i = 0; b && ( i < b->resources.size() ); ++i)
  254. resourceCosts[i] = b->resources[i];
  255. break;
  256. case recruitCreatures:
  257. // Buy upgraded if possible.
  258. ID = whichTown->creaturesToRecruit[which].second.back();
  259. creature = VLC->creh->creatures[ID];
  260. howMany = whichTown->creaturesToRecruit[which].first;
  261. creatures_max = 0; // Max creatures you can recruit of this type.
  262. for (int i = 0; i < creature->cost.size(); i++)
  263. {
  264. if (creature->cost[i] != 0)
  265. creatures_max = hgs.resourceAmounts[i]/creature->cost[i];
  266. else
  267. creatures_max = INT_MAX; // TODO: Will have to rewrite it.
  268. // TODO: Buy the best units (the least I can buy)?
  269. amin(howMany, creatures_max);
  270. }
  271. // The cost of recruiting the stack of creatures.
  272. for (int i = 0; creature && (i < creature->cost.size() ); ++i)
  273. resourceCosts[i] = creature->cost[i]*howMany;
  274. break;
  275. case upgradeCreatures:
  276. UpgradeInfo ui = AI->m_cb->getUpgradeInfo(whichTown->t,which);
  277. ID = whichTown->t->getCreature(which)->idNumber;
  278. howMany = whichTown->t->getStackCount(which);
  279. newID = ui.newID.back();
  280. int upgrade_serial = ui.newID.size() - 1;
  281. for (std::set< std::pair<int,int> >::iterator j = ui.cost[upgrade_serial].begin(); j != ui.cost[upgrade_serial].end(); j++)
  282. resourceCosts[j->first] = j->second*howMany;
  283. break;
  284. }
  285. _cost = AI->m_priorities->getCost(resourceCosts, NULL, 0);
  286. _value = AI->m_priorities->getValue(*this);
  287. return _value - _cost;
  288. }
  289. bool CGeniusAI::TownObjective::operator<(const TownObjective &other) const
  290. {
  291. if (type != other.type)
  292. return type < other.type;
  293. else if (which != other.which)
  294. return which < other.which;
  295. else if (whichTown->t->id != other.whichTown->t->id)
  296. return whichTown->t->id < other.whichTown->t->id;
  297. else
  298. return false;
  299. }
  300. void CGeniusAI::TownObjective::print() const
  301. {
  302. HypotheticalGameState::HeroModel hm;
  303. CBuilding* b = NULL;
  304. const CCreature* creature = NULL;
  305. int ID = 0;
  306. int howMany = 0;
  307. int newID = 0; // TODO: Needed?
  308. int hSlot = 0; // TODO: Needed?
  309. ui32 creatures_max;
  310. switch (type)
  311. {
  312. case recruitHero:
  313. tlog6 << "recruit hero.";
  314. break;
  315. case buildBuilding:
  316. b = VLC->buildh->buildings[whichTown->t->subID][which];
  317. tlog6 << "build " << b->Name() << " cost = ";
  318. if (b->resources.size())
  319. {
  320. if (b->resources[0])
  321. tlog6 << b->resources[0] << " wood. ";
  322. if (b->resources[1])
  323. tlog6 << b->resources[1] << " mercury. ";
  324. if (b->resources[2])
  325. tlog6 << b->resources[2] << " ore. ";
  326. if (b->resources[3])
  327. tlog6 << b->resources[3] << " sulfur. ";
  328. if (b->resources[4])
  329. tlog6 << b->resources[4] << " crystal. ";
  330. if (b->resources[5])
  331. tlog6 << b->resources[5] << " gems. ";
  332. if (b->resources[6])
  333. tlog6 << b->resources[6] << " gold. ";
  334. }
  335. break;
  336. case recruitCreatures:
  337. // Buy upgraded if possible.
  338. ID = whichTown->creaturesToRecruit[which].second.back();
  339. creature = VLC->creh->creatures[ID];
  340. howMany = whichTown->creaturesToRecruit[which].first;
  341. creatures_max = 0;
  342. for (int i = 0; i < creature->cost.size(); i++)
  343. {
  344. if (creature->cost[i])
  345. creatures_max = hgs.resourceAmounts[i]/creature->cost[i];
  346. else
  347. creatures_max = INT_MAX;
  348. amin(howMany, creatures_max);
  349. }
  350. tlog6 << "recruit " << howMany << " " << creature->namePl
  351. << " (Total AI Strength " << creature->AIValue*howMany
  352. << "). cost = ";
  353. if (creature->cost.size())
  354. {
  355. if (creature->cost[0])
  356. tlog6 << creature->cost[0]*howMany << " wood. ";
  357. if (creature->cost[1])
  358. tlog6 << creature->cost[1]*howMany << " mercury. ";
  359. if (creature->cost[2])
  360. tlog6 << creature->cost[2]*howMany << " ore. ";
  361. if (creature->cost[3])
  362. tlog6 << creature->cost[3]*howMany << " sulfur. ";
  363. if (creature->cost[4])
  364. tlog6 << creature->cost[4]*howMany << " cristal. ";
  365. if (creature->cost[5])
  366. tlog6 << creature->cost[5]*howMany << " gems. ";
  367. if (creature->cost[6])
  368. tlog6 << creature->cost[6]*howMany << " gold. ";
  369. }
  370. break; // case recruitCreatures.
  371. case upgradeCreatures:
  372. UpgradeInfo ui = AI->m_cb->getUpgradeInfo (whichTown->t, which);
  373. ID = whichTown->t->getCreature(which)->idNumber;
  374. tlog6 << "upgrade " << VLC->creh->creatures[ID]->namePl;
  375. //ui.cost
  376. break;
  377. } // switch(type)
  378. }
  379. CGeniusAI::CGeniusAI() : m_generalAI(), m_state(NO_BATTLE)
  380. {
  381. m_priorities = new Priorities("AI/GeniusAI.brain");
  382. }
  383. CGeniusAI::~CGeniusAI()
  384. {
  385. delete m_priorities;
  386. }
  387. void CGeniusAI::init(ICallback *CB)
  388. {
  389. m_cb = CB;
  390. m_generalAI.init(CB);
  391. human = false;
  392. playerID = m_cb->getMyColor();
  393. std::string info = std::string("GeniusAI initialized for player ")
  394. + boost::lexical_cast<std::string>(playerID);
  395. m_battleLogic = NULL;
  396. DbgBox(info.c_str());
  397. }
  398. void CGeniusAI::reportResources()
  399. {
  400. tlog6 << "Day " << m_cb->getDate() << ": ";
  401. tlog6 << "AI Player " <<m_cb->getMyColor()<< " with "
  402. << m_cb->howManyHeroes(true) << " heroes. " << endl;
  403. tlog6 << m_cb->getResourceAmount(0) << " wood. ";
  404. tlog6 << m_cb->getResourceAmount(1) << " mercury. ";
  405. tlog6 << m_cb->getResourceAmount(2) << " ore. ";
  406. tlog6 << m_cb->getResourceAmount(3) << " sulfur. ";
  407. tlog6 << m_cb->getResourceAmount(4) << " crystal. ";
  408. tlog6 << m_cb->getResourceAmount(5) << " gems. ";
  409. tlog6 << m_cb->getResourceAmount(6) << " gold.";
  410. tlog6 << endl;
  411. }
  412. void CGeniusAI::addHeroObjectives(CGeniusAI::HypotheticalGameState::HeroModel& h,
  413. CGeniusAI::HypotheticalGameState& hgs)
  414. {
  415. int3 hpos = h.pos;
  416. int3 destination;
  417. int3 interestingPos;
  418. CPath path;
  419. int movement = h.remainingMovement;
  420. int maxInteresting = 0;
  421. AIObjective::Type tp = AIObjective::visit;
  422. if (h.finished)
  423. return;
  424. for (std::set<AIObjectContainer>::const_iterator i = hgs.knownVisitableObjects.begin(); i != hgs.knownVisitableObjects.end(); i++)
  425. {
  426. tp = AIObjective::visit;
  427. if (h.previouslyVisited_pos == i->o->getSightCenter())
  428. continue;
  429. //TODO: what would the hero actually visit if he went to that spot
  430. // maybe the hero wants to visit a seemingly unguarded enemy town,
  431. // but there is a hero on top of it.
  432. // if(i->o->)
  433. if (i->o->ID != HEROI_TYPE)
  434. {// Unless you are trying to visit a hero.
  435. bool heroThere = false;
  436. for(int j = 0; j < hgs.heroModels.size(); j++)
  437. {
  438. if (hgs.heroModels[j].pos == i->o->getSightCenter())
  439. heroThere = true;
  440. }
  441. if (heroThere) // It won't work if there is already someone visiting that spot.
  442. continue;
  443. }
  444. if (i->o->ID == HEROI_TYPE && // Visiting friendly heroes not yet supported.
  445. i->o->getOwner() == m_cb->getMyColor())
  446. continue;
  447. if (i->o->id == h.h->id) // Don't visit yourself (should be caught by above).
  448. continue;
  449. // Don't visit a mine if you own, there's almost no
  450. // point(maybe to leave guards or because the hero's trapped).
  451. if (i->o->ID == 53 && i->o->getOwner() == m_cb->getMyColor())
  452. continue;
  453. if (i->o->getOwner() != m_cb->getMyColor())
  454. {
  455. // TODO: I feel like the AI shouldn't have access to this information.
  456. // We must get an approximation based on few, many, ... zounds etc.
  457. int enemyStrength = 0;
  458. // TODO: should be virtual maybe, army strength should be
  459. // comparable across objects.
  460. // TODO: Rewrite all those damn i->o. For someone reading it the first
  461. // time it's completely inconprehensible.
  462. // TODO: NO MAGIC NUMBERS !!!
  463. if (dynamic_cast<const CArmedInstance*> (i->o))
  464. enemyStrength = (dynamic_cast<const CArmedInstance*> (i->o))->getArmyStrength();
  465. if (dynamic_cast<const CGHeroInstance*> (i->o)) enemyStrength = (dynamic_cast<const CGHeroInstance*> (i->o))->getTotalStrength();
  466. // TODO: Make constants of those 1.2 & 2.5.
  467. if (dynamic_cast<const CGTownInstance*> (i->o))
  468. enemyStrength = static_cast<int>((dynamic_cast<const CGTownInstance*> (i->o))->getArmyStrength() * 1.2);
  469. float heroStrength = h.h->getTotalStrength();
  470. // TODO: ballence these numbers using objective cost formula.
  471. // TODO: it would be nice to do a battle simulation.
  472. if (enemyStrength * 2.5 > heroStrength)
  473. continue;
  474. if (enemyStrength > 0)
  475. tp = AIObjective::attack;
  476. }
  477. //don't visit things that have already been visited this week.
  478. if ((dynamic_cast<const CGVisitableOPW*> (i->o)) &&
  479. (dynamic_cast<const CGVisitableOPW*> (i->o)->visited))
  480. continue;
  481. //don't visit things that you have already visited OPH
  482. if ((dynamic_cast<const CGVisitableOPH*> (i->o)) &&
  483. vstd::contains(dynamic_cast<const CGVisitableOPH*> (i->o)->visitors,
  484. h.h->id))
  485. continue;
  486. // TODO: Some descriptions of those included so someone can undestand them.
  487. if (i->o->ID == 88 || i->o->ID == 89 || i->o->ID == 90)
  488. {
  489. //TODO: if no spell book continue
  490. //TODO: if the shrine's spell is identified, and the hero already has it, continue
  491. }
  492. destination = i->o->getSightCenter();
  493. // Don't try to take a path from the underworld to the top or vice versa.
  494. // TODO: Will have to make some calculations so that the AI can enter the
  495. // underground.
  496. if (hpos.z == destination.z)
  497. {
  498. //TODO: fix get path so that it doesn't return a path unless z's are
  499. // the same, or path goes through sub gate.
  500. if (m_cb->getPath(hpos, destination, h.h, path))
  501. {
  502. path.convert(0);
  503. if (path.nodes[0].dist < movement)
  504. {
  505. // TODO: So easy to understand...
  506. HeroObjective ho(hgs, tp, i->o, &h, this);
  507. std::set<HeroObjective>::iterator found = currentHeroObjectives.find(ho);
  508. if (found == currentHeroObjectives.end())
  509. currentHeroObjectives.insert(ho);
  510. else
  511. {
  512. // TODO: Try to rewrite if possible...
  513. // A cast to a pointer, from a reference, to a pointer
  514. // of an iterator.
  515. HeroObjective* objective = (HeroObjective*)&(*found);
  516. objective->whoCanAchieve.push_back(&h);
  517. }
  518. }
  519. // Find the most interesting object that is eventually reachable,
  520. // and set that position to the ultimate goal position.
  521. // TODO: replace random numbers with some sort of ranking system.
  522. int hi = rand();
  523. if (hi > maxInteresting)
  524. {
  525. maxInteresting = hi;
  526. interestingPos = destination;
  527. }
  528. } // if (m_cb->getPath(hpos, destination, h.h, path))
  529. } // if (hpos.z == destination.z)
  530. } // for (std::set<AIObjectContainer>::const_iterator
  531. // i = knownVisitableObjects.begin();
  532. h.interestingPos = interestingPos;
  533. // there ought to be a path
  534. // if(h.remainingMovement>0&&m_cb->getPath(hpos,interestingPos,h.h,path))
  535. currentHeroObjectives.insert(HeroObjective(hgs,
  536. HeroObjective::finishTurn,
  537. h.h,
  538. &h,
  539. this));
  540. }
  541. void CGeniusAI::HeroObjective::fulfill(CGeniusAI& cg, HypotheticalGameState& hgs)
  542. {
  543. cg.m_cb->waitTillRealize = true;
  544. HypotheticalGameState::HeroModel* h = NULL;
  545. int3 hpos;
  546. int3 destination;
  547. int3 bestPos;
  548. int3 currentPos;
  549. int3 checkPos;
  550. CPath path;
  551. CPath path2;
  552. int howGood = 0;
  553. switch (type)
  554. {
  555. case finishTurn:
  556. h = whoCanAchieve.front();
  557. h->finished=true;
  558. hpos = h->pos;
  559. destination = h->interestingPos;
  560. if (!cg.m_cb->getPath(hpos, destination, h->h, path))
  561. {
  562. tlog6 << "AI error: invalid destination" << endl;
  563. return;
  564. }
  565. destination = h->pos;
  566. // Find closest coord that we can get to.
  567. for (int i = path.nodes.size() - 2; i >= 0; i--)
  568. {
  569. // TODO: getPath what??
  570. if ((cg.m_cb->getPath(hpos, path.nodes[i].coord, h->h, path2)) && (path2.nodes[0].dist <= h->remainingMovement))
  571. destination = path.nodes[i].coord;
  572. }
  573. if (destination == h->interestingPos)
  574. break;
  575. // ! START ! //
  576. // Find close pos with the most neighboring empty squares. We don't want to
  577. // get in the way.
  578. bestPos = destination;
  579. howGood = 0;
  580. // TODO: Add a meaning to 3.
  581. for (int x = -3; x <= 3; x++)
  582. {
  583. for (int y = -3; y <= 3; y++)
  584. {
  585. currentPos = destination + int3(x,y,0);
  586. // There better not be anything there.
  587. if (cg.m_cb->getVisitableObjs(currentPos).size() != 0)
  588. continue;
  589. if ((cg.m_cb->getPath(hpos, currentPos, h->h, path) == false) ||
  590. // It better be reachable from the hero
  591. // TODO: remainingMovement > 0...
  592. (path.nodes[0].dist>h->remainingMovement))
  593. continue;
  594. int count = 0;
  595. int yy;
  596. for (int xx = -1; xx <= 1; ++xx)
  597. {
  598. for (yy = -1; yy <= 1; ++yy)
  599. {
  600. checkPos = currentPos + int3(xx, yy, 0);
  601. if (cg.m_cb->getPath(currentPos, checkPos, h->h, path) != false)
  602. ++count;
  603. }
  604. }
  605. if (count > howGood)
  606. {
  607. howGood = count;
  608. bestPos = currentPos;
  609. }
  610. }
  611. }
  612. destination = bestPos;
  613. // ! END ! //
  614. cg.m_cb->getPath(hpos, destination, h->h, path);
  615. path.convert(0);
  616. break;
  617. case visit:
  618. case attack:
  619. h = whoCanAchieve.front(); //lowest cost hero
  620. h->previouslyVisited_pos = object->getSightCenter();
  621. hpos = h->pos;
  622. destination = object->getSightCenter();
  623. break;
  624. } // switch(type)
  625. if ((type == visit || type == finishTurn || type == attack) && (cg.m_cb->getPath (hpos, destination, h->h, path)))
  626. path.convert(0);
  627. if (cg.m_state.get() != NO_BATTLE)
  628. cg.m_state.waitUntil (NO_BATTLE); // Wait for battle end
  629. // Wait over, battle over too. hero might be killed. check.
  630. for (int i = path.nodes.size() - 2; (i >= 0) && (cg.m_cb->getHeroSerial(h->h) >= 0); --i)
  631. {
  632. if (!cg.m_cb->moveHero(h->h,path.nodes[i].coord));
  633. {
  634. tlog3 << "cannot move hero to " << path.nodes[i].coord << endl;
  635. break;
  636. }
  637. if (cg.m_state.get() != NO_BATTLE)
  638. cg.m_state.waitUntil(NO_BATTLE); // Wait for battle end
  639. }
  640. h->remainingMovement -= path.nodes[0].dist;
  641. if (object->blockVisit)
  642. h->pos = path.nodes[1].coord;
  643. else
  644. h->pos = destination;
  645. std::set<AIObjectContainer>::iterator
  646. i = hgs.knownVisitableObjects.find(AIObjectContainer(object));
  647. if (i != hgs.knownVisitableObjects.end())
  648. hgs.knownVisitableObjects.erase(i);
  649. const CGTownInstance* town = dynamic_cast<const CGTownInstance*> (object);
  650. if (town && object->getOwner() == cg.m_cb->getMyColor())
  651. {
  652. //upgrade hero's units
  653. tlog6 << "visiting town" << endl;
  654. for (TSlots::const_iterator i = h->h->Slots().begin(); i != h->h->Slots().end(); i++)
  655. { // For each hero slot.
  656. UpgradeInfo ui = cg.m_cb->getUpgradeInfo(h->h,i->first);
  657. bool canUpgrade = false;
  658. if (ui.newID.size() != 0)
  659. { // Does this stack need upgrading?
  660. canUpgrade = true;
  661. std::set<std::pair<int,int> >::iterator j;
  662. for (int ii = 0; ii < ui.cost.size(); ii++) // Can afford the upgrade?
  663. {
  664. for (j = ui.cost[ii].begin(); j != ui.cost[ii].end(); j++)
  665. if (hgs.resourceAmounts[j->first] < j->second * i->second->count)
  666. canUpgrade = false;
  667. }
  668. }
  669. if (canUpgrade)
  670. {
  671. cg.m_cb->upgradeCreature(h->h, i->first, ui.newID.back());
  672. tlog6 << "upgrading hero's "
  673. << i->second->type->namePl
  674. << endl;
  675. }
  676. }
  677. // Give town's units to hero.
  678. int weakestCreatureStack;
  679. int weakestCreatureAIValue = 99999; // we will lower it in the process
  680. for (TSlots::const_iterator i = town->Slots().begin(); i != town->Slots().end(); i++)
  681. {
  682. if (i->second->type->AIValue < weakestCreatureAIValue)
  683. {
  684. weakestCreatureAIValue = i->second->type->AIValue;
  685. weakestCreatureStack = i->first;
  686. }
  687. }
  688. for (TSlots::const_iterator i = town->Slots().begin(); i != town->Slots().end(); i++)\
  689. { // For each town slot.
  690. int hSlot = h->h->getSlotFor(i->second->type->idNumber);
  691. if (hSlot == -1)
  692. continue;
  693. tlog6 << "giving hero " << i->second->type->namePl << endl;
  694. if (!h->h->slotEmpty(hSlot))
  695. {
  696. // Can't take garrisonHero's last unit.
  697. if ( (i->first == weakestCreatureStack) && (town->garrisonHero != NULL) )
  698. cg.m_cb->splitStack(town, h->h, i->first, hSlot, i->second->count - 1);
  699. else
  700. // TODO: the comment says that this code is not safe for the AI.
  701. cg.m_cb->mergeStacks(town, h->h, i->first, hSlot);
  702. }
  703. else
  704. cg.m_cb->swapCreatures(town, h->h, i->first, hSlot);
  705. } // for (std::map< si32, std::pair<ui32, si32> >::const_iterator ...
  706. } // if (town && object->getOwner == cg.m_cb->getMyColor())
  707. }
  708. void CGeniusAI::addTownObjectives (HypotheticalGameState::TownModel& t, HypotheticalGameState& hgs)
  709. {
  710. //recruitHero
  711. //buildBuilding
  712. //recruitCreatures
  713. //upgradeCreatures
  714. // Recruit hero.
  715. if ( (hgs.heroModels.size() < 3) && (hgs.resourceAmounts[6] >= 2500) )
  716. {
  717. bool heroAtTown = false;
  718. for (int i = 0; i < hgs.heroModels.size(); i++)
  719. {
  720. if (hgs.heroModels[i].pos == t.t->getSightCenter())
  721. heroAtTown = true;
  722. }
  723. // No visiting hero and built tavern.
  724. if (!heroAtTown && vstd::contains(t.t->builtBuildings, 5))
  725. {
  726. for (int i = 0; i < hgs.AvailableHeroesToBuy.size(); i++)
  727. {
  728. if ( (hgs.AvailableHeroesToBuy[i] != NULL) && (t.t->subID == hgs.AvailableHeroesToBuy[i]->type->heroType / 2) )
  729. {
  730. TownObjective to(hgs,AIObjective::recruitHero, &t, 0, this);
  731. currentTownObjectives.insert(to);
  732. }
  733. }
  734. }
  735. }
  736. // Build a building.
  737. if (!t.hasBuilt)
  738. {
  739. // m_cb->getCBuildingsByID(t.t);
  740. bmap<int, ConstTransitivePtr<CBuilding> > thisTownsBuildings = VLC->buildh->buildings[t.t->subID];
  741. for (bmap<int, ConstTransitivePtr<CBuilding> >::iterator i = thisTownsBuildings.begin(); i != thisTownsBuildings.end(); i++)
  742. {
  743. if (m_cb->canBuildStructure(t.t, i->first) == 7)
  744. {
  745. TownObjective to(hgs, AIObjective::buildBuilding, &t, i->first ,this);
  746. currentTownObjectives.insert(to);
  747. }
  748. }
  749. }
  750. // Recruit creatures.
  751. for (int i = 0; i < t.creaturesToRecruit.size(); i++)
  752. {
  753. if (t.creaturesToRecruit[i].first == 0 || t.creaturesToRecruit[i].second.empty())
  754. continue;
  755. int ID = t.creaturesToRecruit[i].second.back();
  756. // m_cb->getCCreatureByID(ID);
  757. const CCreature *creature = VLC->creh->creatures[ID];
  758. bool canAfford = true;
  759. for (int ii = 0; ii < creature->cost.size(); ii++)
  760. {
  761. if (creature->cost[ii] > hgs.resourceAmounts[ii])
  762. canAfford = false; // Can we afford at least one creature?
  763. }
  764. if (!canAfford)
  765. continue;
  766. //tlog6 << "town has " << t.t->creatures[i]->first << " "<< creature->namePl << " (AI Strength " << creature->AIValue << ")." << endl;
  767. TownObjective to(hgs, AIObjective::recruitCreatures, &t, i, this);
  768. currentTownObjectives.insert(to);
  769. }
  770. // Upgrade creatures.
  771. for (TSlots::const_iterator i = t.t->Slots().begin(); i != t.t->Slots().end(); i++)
  772. {
  773. UpgradeInfo ui = m_cb->getUpgradeInfo(t.t, i->first);
  774. if (ui.newID.size())
  775. {
  776. bool canAfford = true;
  777. int upgrade_serial = ui.newID.size() - 1;
  778. for (std::set< std::pair<int, int> >::iterator j = ui.cost[upgrade_serial].begin(); j != ui.cost[upgrade_serial].end(); j++)
  779. {
  780. if (hgs.resourceAmounts[j->first] < j->second * i->second->count)
  781. canAfford = false;
  782. }
  783. if (canAfford)
  784. {
  785. TownObjective to(hgs,AIObjective::upgradeCreatures,&t,i->first,this);
  786. currentTownObjectives.insert(to);
  787. }
  788. } // if (ui.netID.size() != 0)
  789. } // for (std::map< si32, std::pair ...
  790. }
  791. void CGeniusAI::TownObjective::fulfill(CGeniusAI& cg,
  792. HypotheticalGameState& hgs)
  793. {
  794. cg.m_cb->waitTillRealize = true;
  795. CBuilding * b;
  796. const CCreature *creature;
  797. HypotheticalGameState::HeroModel hm;
  798. int ID, howMany, newID, hSlot;
  799. switch (type)
  800. {
  801. case recruitHero:
  802. cg.m_cb->recruitHero(whichTown->t, hgs.AvailableHeroesToBuy[which]);
  803. hm = HypotheticalGameState::HeroModel(hgs.AvailableHeroesToBuy[which]);
  804. hm.pos = whichTown->t->getSightCenter();
  805. hm.remainingMovement = hm.h->maxMovePoints(true);
  806. hgs.heroModels.push_back(hm);
  807. hgs.resourceAmounts[6] -= 2500;
  808. break;
  809. case buildBuilding:
  810. b = VLC->buildh->buildings[whichTown->t->subID][which];
  811. if (cg.m_cb->canBuildStructure(whichTown->t,which) == 7)
  812. {
  813. tlog6 << "built " << b->Name() << "." << endl;
  814. if (!cg.m_cb->buildBuilding(whichTown->t, which))
  815. tlog6 << "really tried to build unbuildable building" << endl;
  816. for (int i = 0; b && i < b->resources.size(); i++) // use only when certain building was found
  817. hgs.resourceAmounts[i] -= b->resources[i];
  818. } else
  819. tlog6 << "trying to build a structure we cannot build" << endl;
  820. whichTown->hasBuilt=true;
  821. break;
  822. case recruitCreatures:
  823. // Buy upgraded if possible.
  824. ID = whichTown->creaturesToRecruit[which].second.back();
  825. creature = VLC->creh->creatures[ID];
  826. howMany = whichTown->creaturesToRecruit[which].first;
  827. for (int i = 0; i < creature->cost.size(); i++)
  828. amin(howMany, creature->cost[i] ? hgs.resourceAmounts[i]/creature->cost[i] : INT_MAX);
  829. if (howMany == 0)
  830. {
  831. tlog6 << "tried to recruit without enough money.";
  832. tlog6 << "recruiting " << howMany << " "
  833. << creature->namePl << " (Total AI Strength "
  834. << creature->AIValue*howMany << ")." << endl;
  835. cg.m_cb->recruitCreatures(whichTown->t, ID, howMany);
  836. }
  837. break;
  838. case upgradeCreatures:
  839. UpgradeInfo ui = cg.m_cb->getUpgradeInfo(whichTown->t, which);
  840. ID = whichTown->t->getCreature(which)->idNumber;
  841. newID = ui.newID.back();
  842. // TODO: reduce resources in hgs
  843. cg.m_cb->upgradeCreature(whichTown->t, which, newID);
  844. tlog6 << "upgrading " << VLC->creh->creatures[ID]->namePl << endl;
  845. break;
  846. }
  847. }
  848. void CGeniusAI::fillObjectiveQueue(HypotheticalGameState & hgs)
  849. {
  850. objectiveQueue.clear();
  851. currentHeroObjectives.clear();
  852. currentTownObjectives.clear();
  853. for (std::vector <CGeniusAI::HypotheticalGameState::HeroModel>::iterator i = hgs.heroModels.begin(); i != hgs.heroModels.end(); i++)
  854. addHeroObjectives(*i, hgs);
  855. for (std::vector <CGeniusAI::HypotheticalGameState::TownModel>::iterator i = hgs.townModels.begin(); i != hgs.townModels.end(); i++)
  856. addTownObjectives(*i, hgs);
  857. for (std::set<CGeniusAI::HeroObjective>::iterator i = currentHeroObjectives.begin(); i != currentHeroObjectives.end(); i++)
  858. // TODO: Recheck and try to write simpler expression.
  859. objectiveQueue.push_back(AIObjectivePtrCont((CGeniusAI::HeroObjective*)&(*i)));
  860. for (std::set<CGeniusAI::TownObjective>::iterator i = currentTownObjectives.begin(); i != currentTownObjectives.end(); i++)
  861. objectiveQueue.push_back(AIObjectivePtrCont((CGeniusAI::TownObjective*)&(*i)));
  862. }
  863. CGeniusAI::AIObjective * CGeniusAI::getBestObjective()
  864. {
  865. trueGameState.update(*this);
  866. fillObjectiveQueue(trueGameState);
  867. // TODO: Write this part.
  868. // if(objectiveQueue.size())
  869. // return max_element(objectiveQueue.begin(),objectiveQueue.end())->obj;
  870. m_priorities->fillFeatures(trueGameState);
  871. if (objectiveQueue.empty())
  872. return NULL;
  873. // sort(objectiveQueue.begin(),objectiveQueue.end());
  874. // reverse(objectiveQueue.begin(),objectiveQueue.end());
  875. int num = 1;
  876. // for(std::vector<AIObjectivePtrCont> ::iterator i = objectiveQueue.begin(); i < objectiveQueue.end();i++)
  877. // {
  878. // if(!dynamic_cast<HeroObjective*>(i->obj))
  879. // continue;
  880. // tlog6 << num++ << ": ";
  881. // i->obj->print();
  882. // tlog6 << " value: " << i->obj->getValue();
  883. // tlog6 << endl;
  884. // }
  885. // int choice = 0;
  886. // tlog6 << "which would you do? (enter 0 for none): ";
  887. // cin >> choice;
  888. tlog6 << "doing best of " << objectiveQueue.size() << ": ";
  889. CGeniusAI::AIObjective* best = max_element(objectiveQueue.begin(), objectiveQueue.end())->obj;
  890. best->print();
  891. tlog6 << " value = " << best->getValue() << endl;
  892. if (objectiveQueue.size())
  893. return best;
  894. return objectiveQueue.front().obj;
  895. }
  896. void CGeniusAI::yourTurn()
  897. {
  898. static boost::mutex mutex;
  899. boost::mutex::scoped_lock lock(mutex);
  900. m_cb->waitTillRealize = false;
  901. static int seed = rand();
  902. srand(seed);
  903. if (VLC->IS_AI_ENABLED)
  904. {
  905. m_cb->waitTillRealize = true;
  906. // if (m_cb->getDate() == 1)
  907. //{
  908. // startFirstTurn();
  909. //
  910. // m_cb->endTurn();
  911. // return;
  912. // }
  913. //////////////TODO: replace with updates. Also add suspected objects list./////////
  914. knownVisitableObjects.clear();
  915. int3 pos = m_cb->getMapSize();
  916. int y, z; //don't reallocate them unnecessarily
  917. for (int x = 0; x < pos.x; ++x)
  918. {
  919. for (y = 0; y < pos.y; ++y)
  920. {
  921. for (z = 0; z < pos.z; ++z)
  922. tileRevealed(int3(x,y,z));
  923. }
  924. }
  925. ///////////////////////////////////////////////////////////////////////////////////
  926. reportResources();
  927. trueGameState = HypotheticalGameState(*this);
  928. AIObjective * objective = getBestObjective();
  929. if (objective) //single so far, TODO: restore while
  930. objective->fulfill(*this,trueGameState);
  931. seed = rand();
  932. }
  933. m_cb->endTurn();
  934. m_cb->waitTillRealize = false;
  935. }
  936. void CGeniusAI::startFirstTurn()
  937. {
  938. HypotheticalGameState hgs(*this);
  939. const CGTownInstance * town = m_cb->getTownInfo(0,0);
  940. const CGHeroInstance * heroInst = m_cb->getHeroInfo(0,0);
  941. TownObjective(hgs, AIObjective::recruitHero, &hgs.townModels.front(), 0, this).fulfill(*this, hgs);
  942. m_cb->swapGarrisonHero(town);
  943. hgs.update(*this);
  944. for (ui32 i = 0; i < hgs.townModels.front().creaturesToRecruit.size(); ++i)
  945. {
  946. if (hgs.townModels.front().creaturesToRecruit[i].first == 0)
  947. continue;
  948. int ID = hgs.townModels.front().creaturesToRecruit[i].second.back();
  949. const CCreature *creature = VLC->creh->creatures[ID];
  950. bool canAfford = true;
  951. for (ui32 ii = 0; ii < creature->cost.size(); ii++)
  952. {
  953. if (creature->cost[ii] > hgs.resourceAmounts[ii])
  954. canAfford = false; // Can we afford at least one creature?
  955. }
  956. if (!canAfford)
  957. continue;
  958. TownObjective(hgs,AIObjective::recruitCreatures,&hgs.townModels.front(),i,this).fulfill(*this,hgs);
  959. }
  960. hgs.update(*this);
  961. HypotheticalGameState::HeroModel* hero;
  962. for (int i = 0; i < hgs.heroModels.size(); i++)
  963. {
  964. if (hgs.heroModels[i].h->id == heroInst->id)
  965. HeroObjective(hgs, AIObjective::visit, town, hero = &hgs.heroModels[i], this).fulfill(*this,hgs);
  966. }
  967. hgs.update(*this);
  968. // m_cb->swapGarrisonHero(town);
  969. //TODO: choose the strongest hero.
  970. }
  971. void CGeniusAI::heroKilled(const CGHeroInstance* hero)
  972. {
  973. }
  974. void CGeniusAI::heroCreated(const CGHeroInstance* hero)
  975. {
  976. }
  977. void CGeniusAI::tileRevealed(int3 pos)
  978. {
  979. std::vector<const CGObjectInstance*> objects = m_cb->getVisitableObjs(pos);
  980. for (std::vector <const CGObjectInstance*>::iterator o = objects.begin(); o != objects.end(); o++)
  981. {
  982. if ((*o)->id != -1)
  983. knownVisitableObjects.insert(*o);
  984. }
  985. objects = m_cb->getFlaggableObjects(pos);
  986. for (std::vector<const CGObjectInstance*>::iterator o = objects.begin(); o != objects.end(); o++)
  987. if ((*o)->id != -1)
  988. knownVisitableObjects.insert(*o);
  989. }
  990. // eg. ship built in shipyard
  991. void CGeniusAI::newObject(const CGObjectInstance* obj)
  992. {
  993. knownVisitableObjects.insert(obj);
  994. }
  995. void CGeniusAI::objectRemoved(const CGObjectInstance *obj) //eg. collected resource, picked artifact, beaten hero
  996. {
  997. std::set<AIObjectContainer>::iterator o = knownVisitableObjects.find(obj);
  998. if (o != knownVisitableObjects.end())
  999. knownVisitableObjects.erase(o);
  1000. }
  1001. void CGeniusAI::tileHidden(int3 pos)
  1002. {
  1003. }
  1004. void CGeniusAI::heroMoved(const TryMoveHero& TMH)
  1005. {
  1006. // DbgBox("** CGeniusAI::heroMoved **");
  1007. }
  1008. void CGeniusAI::heroGotLevel(const CGHeroInstance *hero,
  1009. int pskill,
  1010. std::vector<ui16>& skills,
  1011. boost::function<void(ui32)>& callback)
  1012. {
  1013. callback(rand() % skills.size());
  1014. }
  1015. void geniusai::CGeniusAI::showGarrisonDialog(const CArmedInstance* up,
  1016. const CGHeroInstance* down,
  1017. bool removableUnits,
  1018. boost::function<void()>& onEnd)
  1019. {
  1020. onEnd();
  1021. }
  1022. void geniusai::CGeniusAI::playerBlocked(int reason)
  1023. {
  1024. if (reason == 0) // Battle is coming...
  1025. m_state.setn(UPCOMING_BATTLE);
  1026. }
  1027. void geniusai::CGeniusAI::battleResultsApplied()
  1028. {
  1029. assert(m_state.get() == ENDING_BATTLE);
  1030. m_state.setn(NO_BATTLE);
  1031. }
  1032. // TODO: Shouldn't the parameters be made const (apart from cancel)?
  1033. void CGeniusAI::showBlockingDialog(const std::string& text,
  1034. const std::vector<Component> &components,
  1035. ui32 askID,
  1036. const int soundID,
  1037. bool selection,
  1038. bool cancel)
  1039. {
  1040. m_cb->selectionMade(cancel ? false : true, askID);
  1041. }
  1042. /**
  1043. * occurs AFTER every action taken by any stack or by the hero
  1044. */
  1045. void CGeniusAI::actionFinished(const BattleAction* action)
  1046. {
  1047. std::string message("\t\tCGeniusAI::actionFinished - type(");
  1048. message += boost::lexical_cast<std::string>((unsigned)action->actionType);
  1049. message += "), side(";
  1050. message += boost::lexical_cast<std::string>((unsigned)action->side);
  1051. message += ")";
  1052. DbgBox(message.c_str());
  1053. }
  1054. /**
  1055. * occurs BEFORE every action taken by any stack or by the hero
  1056. */
  1057. void CGeniusAI::actionStarted(const BattleAction *action)
  1058. {
  1059. std::string message("\t\tCGeniusAI::actionStarted - type(");
  1060. message += boost::lexical_cast<std::string>((unsigned)action->actionType);
  1061. message += "), side(";
  1062. message += boost::lexical_cast<std::string>((unsigned)action->side);
  1063. message += ")";
  1064. DbgBox(message.c_str());
  1065. }
  1066. /**
  1067. * called when stack is performing attack
  1068. */
  1069. void CGeniusAI::battleAttack(const BattleAttack* ba)
  1070. {
  1071. DbgBox("\t\t\tCGeniusAI::battleAttack");
  1072. }
  1073. /**
  1074. * called when stack receives damage (after battleAttack())
  1075. */
  1076. void CGeniusAI::battleStacksAttacked(const std::set<BattleStackAttacked>& bsa)
  1077. {
  1078. DbgBox("\t\t\tCGeniusAI::battleStacksAttacked");
  1079. }
  1080. /**
  1081. * called by engine when battle starts; side=0 - left, side=1 - right
  1082. */
  1083. void CGeniusAI::battleStart(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool side)
  1084. {
  1085. // TODO: Battle logic what...
  1086. assert(!m_battleLogic);
  1087. // We have been informed that battle will start (or we are neutral AI)
  1088. assert( (playerID > PLAYER_LIMIT) || (m_state.get() == UPCOMING_BATTLE) );
  1089. m_state.setn(ONGOING_BATTLE);
  1090. m_battleLogic = new BattleAI::CBattleLogic(m_cb, army1, army2, tile, hero1,
  1091. hero2, side);
  1092. DbgBox("** CGeniusAI::battleStart **");
  1093. }
  1094. /**
  1095. *
  1096. */
  1097. void CGeniusAI::battleEnd(const BattleResult* br)
  1098. {
  1099. switch (br->winner)
  1100. {
  1101. case 0: tlog6 << "The winner is the attacker." << std::endl; break;
  1102. case 1: tlog6 << "The winner is the defender." << std::endl; break;
  1103. case 2: tlog6 << "It's a draw." << std::endl; break;
  1104. };
  1105. tlog6 << "lost ";
  1106. for (std::map<ui32,si32>::const_iterator i = br->casualties[0].begin(); i != br->casualties[0].end(); i++)
  1107. tlog6 << i->second << " " << VLC->creh->creatures[i->first]->namePl << endl;
  1108. delete m_battleLogic;
  1109. m_battleLogic = NULL;
  1110. assert(m_state.get() == ONGOING_BATTLE);
  1111. m_state.setn(ENDING_BATTLE);
  1112. DbgBox("** CGeniusAI::battleEnd **");
  1113. }
  1114. /*
  1115. * Called at the beggining of each turn, round = -1 is the tactic phase,
  1116. * round = 0 is the first "normal" turn.
  1117. */
  1118. void CGeniusAI::battleNewRound(int round)
  1119. {
  1120. std::string message("\tCGeniusAI::battleNewRound - ");
  1121. message += boost::lexical_cast<std::string>(round);
  1122. DbgBox(message.c_str());
  1123. m_battleLogic->SetCurrentTurn(round);
  1124. }
  1125. /**
  1126. *
  1127. */
  1128. void CGeniusAI::battleStackMoved(int ID, int dest, int distance, bool end)
  1129. {
  1130. std::string message("\t\t\tCGeniusAI::battleStackMoved ID(");
  1131. message += boost::lexical_cast<std::string>(ID);
  1132. message += "), dest(";
  1133. message += boost::lexical_cast<std::string>(dest);
  1134. message += ")";
  1135. DbgBox(message.c_str());
  1136. }
  1137. /**
  1138. *
  1139. */
  1140. void CGeniusAI::battleSpellCast(const BattleSpellCast *sc)
  1141. {
  1142. DbgBox("\t\t\tCGeniusAI::battleSpellCast");
  1143. }
  1144. /**
  1145. * called when battlefield is prepared, prior the battle beginning
  1146. */
  1147. // void CGeniusAI::battlefieldPrepared(int battlefieldType,
  1148. // std::vector<CObstacle*> obstacles)
  1149. // {
  1150. // DbgBox("CGeniusAI::battlefieldPrepared");
  1151. // }
  1152. /**
  1153. *
  1154. */
  1155. void CGeniusAI::battleStackMoved(int ID,
  1156. int dest,
  1157. bool startMoving,
  1158. bool endMoving)
  1159. {
  1160. DbgBox("\t\t\tCGeniusAI::battleStackMoved");
  1161. }
  1162. /**
  1163. *
  1164. */
  1165. void CGeniusAI::battleStackAttacking(int ID, int dest)
  1166. {
  1167. DbgBox("\t\t\tCGeniusAI::battleStackAttacking");
  1168. }
  1169. /**
  1170. *
  1171. */
  1172. void CGeniusAI::battleStackIsAttacked(int ID,
  1173. int dmg,
  1174. int killed,
  1175. int IDby,
  1176. bool byShooting)
  1177. {
  1178. DbgBox("\t\t\tCGeniusAI::battleStackIsAttacked");
  1179. }
  1180. /**
  1181. * called when it's turn of that stack
  1182. */
  1183. BattleAction CGeniusAI::activeStack(int stackID)
  1184. {
  1185. std::string message("\t\t\tCGeniusAI::activeStack stackID(");
  1186. message += boost::lexical_cast<std::string>(stackID);
  1187. message += ")";
  1188. DbgBox(message.c_str());
  1189. BattleAction bact = m_battleLogic->MakeDecision(stackID);
  1190. assert(m_cb->battleGetStackByID(bact.stackNumber));
  1191. return bact;
  1192. };