CGeniusAI.cpp 42 KB

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