CGeniusAI.cpp 39 KB

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