CGeniusAI.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050
  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. HeroObjective *objective = (HeroObjective *)&(*found);
  321. objective->whoCanAchieve.push_back(&h);
  322. }
  323. }
  324. // find the most interesting object that is eventually reachable, and set that position to the ultimate goal position
  325. int hi = rand(); //TODO: replace random numbers with some sort of ranking system
  326. if(hi>maxInteresting)
  327. {
  328. maxInteresting = hi;
  329. interestingPos = destination;
  330. }
  331. }
  332. }
  333. }
  334. h.interestingPos = interestingPos;
  335. if(h.remainingMovement>0&&m_cb->getPath(hpos,interestingPos,h.h,path)) // there ought to be a path
  336. currentHeroObjectives.insert(HeroObjective(HeroObjective::finishTurn,h.h,&h,this));
  337. }
  338. void CGeniusAI::HeroObjective::fulfill(CGeniusAI & cg,HypotheticalGameState & hgs)
  339. {
  340. cg.m_cb->waitTillRealize = true;
  341. HypotheticalGameState::HeroModel * h;
  342. int3 hpos, destination;
  343. CPath path;
  344. CPath path2;
  345. int3 bestPos,currentPos,checkPos;
  346. int howGood;
  347. switch(type)
  348. {
  349. case finishTurn:
  350. h = whoCanAchieve.front();
  351. hpos = h->pos;
  352. destination = h->interestingPos;
  353. if(!cg.m_cb->getPath(hpos,destination,h->h,path)) {cout << "AI error: invalid destination" << endl; return;}
  354. // path.convert(0);
  355. destination = h->pos;
  356. for(int i = path.nodes.size()-2;i>=0;i--) //find closest coord that we can get to
  357. if(cg.m_cb->getPath(hpos,path.nodes[i].coord,h->h,path2)&&path2.nodes[0].dist<=h->remainingMovement)
  358. destination = path.nodes[i].coord;
  359. if(destination == h->interestingPos) break;
  360. ///////// Find close pos with the most neighboring empty squares. We don't want to get in the way. ///////////////////
  361. bestPos = destination;
  362. howGood=0;
  363. for(int x = -3;x <= 3;x++)
  364. for(int y = -3;y <= 3;y++)
  365. {
  366. currentPos=destination+int3(x,y,0);
  367. if(cg.m_cb->getVisitableObjs(currentPos).size()!=0) //there better not be anything there
  368. continue;
  369. if(!cg.m_cb->getPath(hpos,currentPos,h->h,path)||path.nodes[0].dist>h->remainingMovement) //it better be reachable from the hero
  370. continue;
  371. int count = 0;
  372. for(int xx = -1;xx <= 1;xx++)
  373. for(int yy = -1;yy <= 1;yy++)
  374. {
  375. checkPos = currentPos+int3(xx,yy,0);
  376. if(cg.m_cb->getPath(currentPos,checkPos,h->h,path))
  377. count++;
  378. }
  379. if(count > howGood)
  380. {
  381. howGood = count;
  382. bestPos = currentPos;
  383. }
  384. }
  385. destination = bestPos;
  386. h->finished=true;
  387. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  388. break;
  389. case visit:case attack:
  390. float bestCost = 9e9;
  391. int bestHero = 0;
  392. vector<int> resourceCosts;
  393. for(int i = 0; i < 8;i++)
  394. resourceCosts.push_back(0);
  395. for(int i = 0; i < whoCanAchieve.size();i++)
  396. {
  397. int distOutOfTheWay = 0;
  398. CPath path;
  399. //from hero to object
  400. if(AI->m_cb->getPath(whoCanAchieve[i]->pos,pos,whoCanAchieve[i]->h,path)) distOutOfTheWay+=path.nodes[0].dist;
  401. //from object to goal
  402. if(AI->m_cb->getPath(pos,whoCanAchieve[i]->interestingPos,whoCanAchieve[i]->h,path))
  403. {
  404. distOutOfTheWay+=path.nodes[0].dist;
  405. //from hero directly to goal
  406. if(AI->m_cb->getPath(whoCanAchieve[i]->pos,whoCanAchieve[i]->interestingPos,whoCanAchieve[i]->h,path)) distOutOfTheWay-=path.nodes[0].dist;
  407. }
  408. float cost = CostModel(resourceCosts,whoCanAchieve[i]->h,distOutOfTheWay).getCost();
  409. if(cost < bestCost)
  410. {
  411. bestCost = cost;
  412. bestHero = i;
  413. }
  414. }
  415. h = whoCanAchieve[bestHero];//TODO:replace with best hero for the job
  416. //if(dynamic_cast<const CGVisitableOPH *> (object))
  417. // std::cout << h->h->name << " is visiting " << object->hoverName << std::endl;
  418. hpos = h->pos;
  419. destination = object->getSightCenter();
  420. break;
  421. }
  422. if(type == visit||type == finishTurn)
  423. if(cg.m_cb->getPath(hpos,destination,h->h,path))
  424. {
  425. path.convert(0);
  426. if(cg.m_state.get() != NO_BATTLE)
  427. cg.m_state.waitUntil(NO_BATTLE);//wait for battle end
  428. //wait over, battle over too. hero might be killed. check.
  429. for(int i = path.nodes.size()-2;i>=0&&(cg.m_cb->getHeroSerial(h->h) >= 0);i--)
  430. {
  431. cg.m_cb->moveHero(h->h,path.nodes[i].coord);
  432. if(cg.m_state.get() != NO_BATTLE)
  433. cg.m_state.waitUntil(NO_BATTLE);//wait for battle end
  434. }
  435. h->remainingMovement-=path.nodes[0].dist;
  436. if(object->blockVisit)
  437. h->pos = path.nodes[1].coord;
  438. else
  439. h->pos=destination;
  440. std::set<AIObjectContainer>::iterator i = hgs.knownVisitableObjects.find(AIObjectContainer(object));
  441. if(i!=hgs.knownVisitableObjects.end())
  442. hgs.knownVisitableObjects.erase(i);
  443. }
  444. const CGTownInstance * town = dynamic_cast<const CGTownInstance *> (object);
  445. if(town&&object->getOwner()==cg.m_cb->getMyColor())
  446. {
  447. //upgrade hero's units
  448. cout << "visiting town" << endl;
  449. CCreatureSet hcreatures = h->h->army;
  450. for(std::map<si32,std::pair<ui32,si32> >::const_iterator i = hcreatures.slots.begin();i!=hcreatures.slots.end();i++) // for each hero slot
  451. {
  452. UpgradeInfo ui = cg.m_cb->getUpgradeInfo(h->h,i->first);
  453. bool canUpgrade = false;
  454. if(ui.newID.size()!=0) //does this stack need upgrading?
  455. {
  456. canUpgrade = true;
  457. for(int ii=0;ii<ui.cost.size();ii++)//can afford the upgrade?
  458. for (std::set<std::pair<int,int> >::iterator j=ui.cost[ii].begin(); j!=ui.cost[ii].end(); j++)
  459. if(hgs.resourceAmounts[j->first] < j->second*i->second.second)
  460. canUpgrade = false;
  461. }
  462. if(canUpgrade)
  463. {
  464. cg.m_cb->upgradeCreature(h->h,i->first,ui.newID.back());
  465. cout << "upgrading hero's " << VLC->creh->creatures[i->second.first].namePl << endl;
  466. }
  467. }
  468. //give town's units to hero
  469. CCreatureSet tcreatures = town->army;
  470. int weakestCreatureStack;
  471. int weakestCreatureAIValue=99999;
  472. for(std::map<si32,std::pair<ui32,si32> >::const_iterator i = tcreatures.slots.begin();i!=tcreatures.slots.end();i++)
  473. if(VLC->creh->creatures[i->second.first].AIValue<weakestCreatureAIValue)
  474. {
  475. weakestCreatureAIValue = VLC->creh->creatures[i->second.first].AIValue;
  476. weakestCreatureStack = i->first;
  477. }
  478. for(std::map<si32,std::pair<ui32,si32> >::const_iterator i = tcreatures.slots.begin();i!=tcreatures.slots.end();i++) // for each town slot
  479. {
  480. hcreatures = h->h->army;
  481. int hSlot = hcreatures.getSlotFor(i->second.first);
  482. if(hSlot == -1) continue;
  483. cout << "giving hero " << VLC->creh->creatures[i->second.first].namePl << endl;
  484. if(hcreatures.slots.find(hSlot)!=hcreatures.slots.end())
  485. {
  486. if(i->first==weakestCreatureStack&&town->garrisonHero!=NULL)//can't take garrisonHero's last unit
  487. cg.m_cb->splitStack(town,h->h,i->first,hSlot,i->second.second-1);
  488. else
  489. cg.m_cb->mergeStacks(town,h->h,i->first,hSlot); //TODO: the comment says that this code is not safe for the AI.
  490. }
  491. else
  492. {
  493. cg.m_cb->swapCreatures(town,h->h,i->first,hSlot);
  494. }
  495. }
  496. }
  497. }
  498. void CGeniusAI::addTownObjectives(HypotheticalGameState::TownModel &t, HypotheticalGameState & hgs)
  499. {
  500. //recruitHero
  501. //buildBuilding
  502. //recruitCreatures
  503. //upgradeCreatures
  504. if(hgs.heroModels.size()<3&&hgs.resourceAmounts[6]>=2500) //recruitHero
  505. {
  506. bool heroAtTown = false;
  507. for(int i = 0; i < hgs.heroModels.size();i++)
  508. if(hgs.heroModels[i].pos==t.t->getSightCenter())
  509. heroAtTown = true;
  510. if(!heroAtTown && vstd::contains(t.t->builtBuildings, 5)) //no visiting hero and built tavern
  511. {
  512. for(int i =0; i < hgs.AvailableHeroesToBuy.size();i++)
  513. if(hgs.AvailableHeroesToBuy[i]!=NULL&&(t.t->subID==(hgs.AvailableHeroesToBuy[i]->type->heroType/2)))
  514. {
  515. TownObjective to(AIObjective::recruitHero,&t,0,this);
  516. currentTownObjectives.insert(to);
  517. }
  518. }
  519. }
  520. //buildBuilding
  521. if(!t.hasBuilt)
  522. {
  523. std::map<int, CBuilding *> thisTownsBuildings = VLC->buildh->buildings[t.t->subID];// m_cb->getCBuildingsByID(t.t);
  524. for(std::map<int, CBuilding *>::iterator i = thisTownsBuildings.begin(); i != thisTownsBuildings.end();i++)
  525. {
  526. if(m_cb->canBuildStructure(t.t,i->first)==7)
  527. {
  528. TownObjective to(AIObjective::buildBuilding,&t,i->first,this);
  529. currentTownObjectives.insert(to);
  530. //cout <<"can build " << i->first << " "<< i->second->Name() << endl;
  531. }
  532. }
  533. }
  534. //recruitCreatures
  535. for(int i = 0; i < t.creaturesToRecruit.size() ;i++)
  536. {
  537. if(t.creaturesToRecruit[i].first==0||t.creaturesToRecruit[i].second.empty()) continue;
  538. int ID = t.creaturesToRecruit[i].second.back();
  539. const CCreature *creature = &VLC->creh->creatures[ID];//m_cb->getCCreatureByID(ID);
  540. bool canAfford = true;
  541. for(int ii = 0;ii<creature->cost.size();ii++)
  542. if(creature->cost[ii]>hgs.resourceAmounts[ii])
  543. canAfford = false; // can we afford at least one creature?
  544. if(!canAfford) continue;
  545. //cout << "town has " << t.t->creatures[i].first << " "<< creature->namePl << " (AI Strength " << creature->AIValue << ")." << endl;
  546. TownObjective to(AIObjective::recruitCreatures,&t,i,this);
  547. currentTownObjectives.insert(to);
  548. }
  549. //upgradeCreatures
  550. for(std::map<si32,std::pair<ui32,si32> >::iterator i = t.creaturesInGarrison.slots.begin();i!=t.creaturesInGarrison.slots.end();i++)
  551. {
  552. UpgradeInfo ui = m_cb->getUpgradeInfo(t.t,i->first);
  553. if(ui.newID.size()!=0)
  554. {
  555. bool canAfford = true;
  556. for(int ii=0;ii<ui.cost.size();ii++)
  557. for (std::set<std::pair<int,int> >::iterator j=ui.cost[ii].begin(); j!=ui.cost[ii].end(); j++)
  558. if(hgs.resourceAmounts[j->first] < j->second*i->second.second)
  559. canAfford = false;
  560. if(canAfford)
  561. {
  562. TownObjective to(AIObjective::upgradeCreatures,&t,i->first,this);
  563. currentTownObjectives.insert(to);
  564. }
  565. }
  566. }
  567. }
  568. void CGeniusAI::TownObjective::fulfill(CGeniusAI & cg,HypotheticalGameState &hgs)
  569. {
  570. cg.m_cb->waitTillRealize = true;
  571. CBuilding * b;
  572. const CCreature *creature;
  573. HypotheticalGameState::HeroModel hm;
  574. int ID, howMany, newID, hSlot;
  575. switch(type)
  576. {
  577. case recruitHero:
  578. cg.m_cb->recruitHero(whichTown->t,hgs.AvailableHeroesToBuy[which]);
  579. hm = HypotheticalGameState::HeroModel(hgs.AvailableHeroesToBuy[which]);
  580. hm.pos = whichTown->t->getSightCenter();
  581. hm.remainingMovement = hm.h->maxMovePoints(true);
  582. hgs.heroModels.push_back(hm);
  583. hgs.resourceAmounts[6]-=2500;
  584. break;
  585. case buildBuilding:
  586. b = VLC->buildh->buildings[whichTown->t->subID][which];
  587. if(cg.m_cb->canBuildStructure(whichTown->t,which)==7)
  588. {
  589. cout << "built " << b->Name() << "." << endl;
  590. if(!cg.m_cb->buildBuilding(whichTown->t,which)) cout << "really tried to build unbuildable building" <<endl;
  591. for(int i = 0; b && i < b->resources.size();i++)
  592. hgs.resourceAmounts[i]-=b->resources[i];
  593. }
  594. else cout << "trying to build a structure we cannot build" << endl;
  595. whichTown->hasBuilt=true;
  596. break;
  597. case recruitCreatures:
  598. ID = whichTown->creaturesToRecruit[which].second.back(); //buy upgraded if possible
  599. creature = &VLC->creh->creatures[ID];
  600. howMany = whichTown->creaturesToRecruit[which].first;
  601. for(int i = 0; i < creature->cost.size();i++)
  602. amin(howMany,creature->cost[i]?hgs.resourceAmounts[i]/creature->cost[i]:INT_MAX);
  603. if(howMany == 0) cout << "tried to recruit without enough money.";
  604. cout << "recruiting " << howMany << " "<< creature->namePl << " (Total AI Strength " << creature->AIValue*howMany << ")." << endl;
  605. cg.m_cb->recruitCreatures(whichTown->t,ID,howMany);
  606. break;
  607. case upgradeCreatures:
  608. UpgradeInfo ui = cg.m_cb->getUpgradeInfo(whichTown->t,which);
  609. ID = whichTown->creaturesInGarrison.slots[which].first;
  610. newID = ui.newID.back();
  611. cg.m_cb->upgradeCreature(whichTown->t,which,newID);//TODO: reduce resources in hgs
  612. cout << "upgrading " << VLC->creh->creatures[ID].namePl << endl;
  613. break;
  614. }
  615. }
  616. void CGeniusAI::fillObjectiveQueue(HypotheticalGameState & hgs)
  617. {
  618. objectiveQueue.clear();
  619. currentHeroObjectives.clear();
  620. currentTownObjectives.clear();
  621. for(std::vector <CGeniusAI::HypotheticalGameState::HeroModel>::iterator i = hgs.heroModels.begin(); i != hgs.heroModels.end(); i++)
  622. addHeroObjectives(*i,hgs);
  623. for(std::vector <CGeniusAI::HypotheticalGameState::TownModel>::iterator i = hgs.townModels.begin(); i != hgs.townModels.end(); i++)
  624. addTownObjectives(*i,hgs);
  625. for(std::set<CGeniusAI::HeroObjective>::iterator i = currentHeroObjectives.begin(); i != currentHeroObjectives.end(); i++)
  626. objectiveQueue.push_back(AIObjectivePtrCont((CGeniusAI::HeroObjective *)&(*i)));
  627. for(std::set<CGeniusAI::TownObjective>::iterator i = currentTownObjectives.begin(); i != currentTownObjectives.end(); i++)
  628. objectiveQueue.push_back(AIObjectivePtrCont((CGeniusAI::TownObjective *)&(*i)));
  629. }
  630. CGeniusAI::AIObjective * CGeniusAI::getBestObjective()
  631. {
  632. trueGameState.update(*this);
  633. fillObjectiveQueue(trueGameState);
  634. // if(!objectiveQueue.empty())
  635. // return max_element(objectiveQueue.begin(),objectiveQueue.end())->obj;
  636. if(objectiveQueue.empty()) return NULL;
  637. sort(objectiveQueue.begin(),objectiveQueue.end());
  638. int num= 1;
  639. for(std::vector<AIObjectivePtrCont> ::iterator i = objectiveQueue.begin(); i < objectiveQueue.end();i++)
  640. {
  641. cout << num++ << ": ";
  642. i->obj->print();
  643. cout << endl;
  644. }
  645. return objectiveQueue.front().obj;
  646. }
  647. void CGeniusAI::yourTurn()
  648. {
  649. static boost::mutex mutex;
  650. boost::mutex::scoped_lock lock(mutex);
  651. m_cb->waitTillRealize = true;
  652. static int seed = rand();
  653. srand(seed);
  654. if(m_cb->getDate()==1)
  655. {
  656. // startFirstTurn();
  657. // m_cb->endTurn();
  658. // return;
  659. }
  660. //////////////TODO: replace with updates. Also add suspected objects list./////////
  661. knownVisitableObjects.clear();
  662. int3 pos = m_cb->getMapSize();
  663. for(int x = 0;x<pos.x;x++)
  664. for(int y = 0;y<pos.y;y++)
  665. for(int z = 0;z<pos.z;z++)
  666. tileRevealed(int3(x,y,z));
  667. ///////////////////////////////////////////////////////////////////////////////////
  668. reportResources();
  669. trueGameState = HypotheticalGameState(*this);
  670. AIObjective * objective;
  671. while((objective = getBestObjective())!=NULL)
  672. objective->fulfill(*this,trueGameState);
  673. seed = rand();
  674. m_cb->endTurn();
  675. m_cb->waitTillRealize = false;
  676. }
  677. void CGeniusAI::startFirstTurn()
  678. {
  679. HypotheticalGameState hgs(*this);
  680. const CGTownInstance * town = m_cb->getTownInfo(0,0);
  681. const CGHeroInstance * heroInst = m_cb->getHeroInfo(0,0);
  682. TownObjective(AIObjective::recruitHero,&hgs.townModels.front(),0,this).fulfill(*this,hgs);
  683. m_cb->swapGarrisonHero(town);
  684. hgs.update(*this);
  685. for(int i = 0; i < hgs.townModels.front().creaturesToRecruit.size() ;i++)
  686. {
  687. if(hgs.townModels.front().creaturesToRecruit[i].first==0) continue;
  688. int ID = hgs.townModels.front().creaturesToRecruit[i].second.back();
  689. const CCreature *creature = &VLC->creh->creatures[ID];
  690. bool canAfford = true;
  691. for(int ii = 0;ii<creature->cost.size();ii++)
  692. if(creature->cost[ii]>hgs.resourceAmounts[ii])
  693. canAfford = false; // can we afford at least one creature?
  694. if(!canAfford) continue;
  695. TownObjective(AIObjective::recruitCreatures,&hgs.townModels.front(),i,this).fulfill(*this,hgs);
  696. }
  697. hgs.update(*this);
  698. HypotheticalGameState::HeroModel *hero;
  699. for(int i = 0; i < hgs.heroModels.size();i++)
  700. if(hgs.heroModels[i].h->id==heroInst->id)
  701. HeroObjective(AIObjective::visit,town,hero=&hgs.heroModels[i],this).fulfill(*this,hgs);
  702. hgs.update(*this);
  703. // m_cb->swapGarrisonHero(town);
  704. //TODO: choose the strongest hero.
  705. }
  706. void CGeniusAI::heroKilled(const CGHeroInstance * hero)
  707. {
  708. }
  709. void CGeniusAI::heroCreated(const CGHeroInstance *hero)
  710. {
  711. }
  712. void CGeniusAI::tileRevealed(int3 pos)
  713. {
  714. std::vector < const CGObjectInstance * > objects = m_cb->getVisitableObjs(pos);
  715. for(std::vector < const CGObjectInstance * >::iterator o = objects.begin();o!=objects.end();o++)
  716. if((*o)->id!=-1)
  717. knownVisitableObjects.insert(*o);
  718. objects = m_cb->getFlaggableObjects(pos);
  719. for(std::vector < const CGObjectInstance * >::iterator o = objects.begin();o!=objects.end();o++)
  720. if((*o)->id!=-1)
  721. knownVisitableObjects.insert(*o);
  722. }
  723. void CGeniusAI::newObject(const CGObjectInstance * obj) //eg. ship built in shipyard
  724. {
  725. knownVisitableObjects.insert(obj);
  726. }
  727. void CGeniusAI::objectRemoved(const CGObjectInstance *obj) //eg. collected resource, picked artifact, beaten hero
  728. {
  729. std::set <AIObjectContainer>::iterator o = knownVisitableObjects.find(obj);
  730. if(o!=knownVisitableObjects.end())
  731. knownVisitableObjects.erase(o);
  732. }
  733. void CGeniusAI::tileHidden(int3 pos)
  734. {
  735. }
  736. void CGeniusAI::heroMoved(const TryMoveHero &TMH)
  737. {
  738. //DbgBox("** CGeniusAI::heroMoved **");
  739. }
  740. void CGeniusAI::heroGotLevel(const CGHeroInstance *hero, int pskill, std::vector<ui16> &skills, boost::function<void(ui32)> &callback)
  741. {
  742. callback(rand() % skills.size());
  743. }
  744. void GeniusAI::CGeniusAI::showGarrisonDialog( const CArmedInstance *up, const CGHeroInstance *down, boost::function<void()> &onEnd )
  745. {
  746. onEnd();
  747. }
  748. void GeniusAI::CGeniusAI::playerBlocked( int reason )
  749. {
  750. if(reason == 0) //battle is coming...
  751. {
  752. m_state.setn(UPCOMING_BATTLE);
  753. }
  754. }
  755. void GeniusAI::CGeniusAI::battleResultsApplied()
  756. {
  757. assert(m_state.get() == ENDING_BATTLE);
  758. m_state.setn(NO_BATTLE);
  759. }
  760. void CGeniusAI::showBlockingDialog(const std::string &text, const std::vector<Component> &components, ui32 askID, const int soundID, bool selection, bool cancel)
  761. {
  762. m_cb->selectionMade(cancel ? 0 : 1, askID);
  763. }
  764. /**
  765. * occurs AFTER every action taken by any stack or by the hero
  766. */
  767. void CGeniusAI::actionFinished(const BattleAction *action)
  768. {
  769. std::string message("\t\tCGeniusAI::actionFinished - type(");
  770. message += boost::lexical_cast<std::string>((unsigned)action->actionType);
  771. message += "), side(";
  772. message += boost::lexical_cast<std::string>((unsigned)action->side);
  773. message += ")";
  774. DbgBox(message.c_str());
  775. }
  776. /**
  777. * occurs BEFORE every action taken by any stack or by the hero
  778. */
  779. void CGeniusAI::actionStarted(const BattleAction *action)
  780. {
  781. std::string message("\t\tCGeniusAI::actionStarted - type(");
  782. message += boost::lexical_cast<std::string>((unsigned)action->actionType);
  783. message += "), side(";
  784. message += boost::lexical_cast<std::string>((unsigned)action->side);
  785. message += ")";
  786. DbgBox(message.c_str());
  787. }
  788. /**
  789. * called when stack is performing attack
  790. */
  791. void CGeniusAI::battleAttack(BattleAttack *ba)
  792. {
  793. DbgBox("\t\t\tCGeniusAI::battleAttack");
  794. }
  795. /**
  796. * called when stack receives damage (after battleAttack())
  797. */
  798. void CGeniusAI::battleStacksAttacked(std::set<BattleStackAttacked> & bsa)
  799. {
  800. DbgBox("\t\t\tCGeniusAI::battleStacksAttacked");
  801. }
  802. /**
  803. * called by engine when battle starts; side=0 - left, side=1 - right
  804. */
  805. void CGeniusAI::battleStart(CCreatureSet *army1, CCreatureSet *army2, int3 tile, CGHeroInstance *hero1, CGHeroInstance *hero2, bool side)
  806. {
  807. assert(!m_battleLogic);
  808. assert(playerID > PLAYER_LIMIT || m_state.get() == UPCOMING_BATTLE); //we have been informed that battle will start (or we are neutral AI)
  809. m_state.setn(ONGOING_BATTLE);
  810. m_battleLogic = new BattleAI::CBattleLogic(m_cb, army1, army2, tile, hero1, hero2, side);
  811. DbgBox("** CGeniusAI::battleStart **");
  812. }
  813. /**
  814. *
  815. */
  816. void CGeniusAI::battleEnd(BattleResult *br)
  817. {
  818. switch(br->winner)
  819. {
  820. case 0: std::cout << "The winner is the attacker." << std::endl;break;
  821. case 1: std::cout << "The winner is the defender." << std::endl;break;
  822. case 2: std::cout << "It's a draw." << std::endl;break;
  823. };
  824. delete m_battleLogic;
  825. m_battleLogic = NULL;
  826. assert(m_state.get() == ONGOING_BATTLE);
  827. m_state.setn(ENDING_BATTLE);
  828. DbgBox("** CGeniusAI::battleEnd **");
  829. }
  830. /**
  831. * called at the beggining of each turn, round=-1 is the tactic phase, round=0 is the first "normal" turn
  832. */
  833. void CGeniusAI::battleNewRound(int round)
  834. {
  835. std::string message("\tCGeniusAI::battleNewRound - ");
  836. message += boost::lexical_cast<std::string>(round);
  837. DbgBox(message.c_str());
  838. m_battleLogic->SetCurrentTurn(round);
  839. }
  840. /**
  841. *
  842. */
  843. void CGeniusAI::battleStackMoved(int ID, int dest, int distance, bool end)
  844. {
  845. std::string message("\t\t\tCGeniusAI::battleStackMoved ID(");
  846. message += boost::lexical_cast<std::string>(ID);
  847. message += "), dest(";
  848. message += boost::lexical_cast<std::string>(dest);
  849. message += ")";
  850. DbgBox(message.c_str());
  851. }
  852. /**
  853. *
  854. */
  855. void CGeniusAI::battleSpellCast(SpellCast *sc)
  856. {
  857. DbgBox("\t\t\tCGeniusAI::battleSpellCast");
  858. }
  859. /**
  860. * called when battlefield is prepared, prior the battle beginning
  861. */
  862. void CGeniusAI::battlefieldPrepared(int battlefieldType, std::vector<CObstacle*> obstacles)
  863. {
  864. DbgBox("CGeniusAI::battlefieldPrepared");
  865. }
  866. /**
  867. *
  868. */
  869. void CGeniusAI::battleStackMoved(int ID, int dest, bool startMoving, bool endMoving)
  870. {
  871. DbgBox("\t\t\tCGeniusAI::battleStackMoved");
  872. }
  873. /**
  874. *
  875. */
  876. void CGeniusAI::battleStackAttacking(int ID, int dest)
  877. {
  878. DbgBox("\t\t\tCGeniusAI::battleStackAttacking");
  879. }
  880. /**
  881. *
  882. */
  883. void CGeniusAI::battleStackIsAttacked(int ID, int dmg, int killed, int IDby, bool byShooting)
  884. {
  885. DbgBox("\t\t\tCGeniusAI::battleStackIsAttacked");
  886. }
  887. /**
  888. * called when it's turn of that stack
  889. */
  890. BattleAction CGeniusAI::activeStack(int stackID)
  891. {
  892. std::string message("\t\t\tCGeniusAI::activeStack stackID(");
  893. message += boost::lexical_cast<std::string>(stackID);
  894. message += ")";
  895. DbgBox(message.c_str());
  896. return m_battleLogic->MakeDecision(stackID);
  897. };