CGeniusAI.cpp 42 KB

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