CGeniusAI.cpp 42 KB

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