CGeniusAI.cpp 33 KB

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