CGeniusAI.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. #include "CGeniusAI.h"
  2. #include <iostream>
  3. using namespace std;
  4. using namespace GeniusAI;
  5. #if defined (_MSC_VER) && (_MSC_VER >= 1020) || (__MINGW32__)
  6. #include <windows.h>
  7. #endif
  8. void DbgBox(const char *msg, bool messageBox)
  9. {
  10. #if defined PRINT_DEBUG
  11. #if defined _DEBUG
  12. //#if 0
  13. # if defined (_MSC_VER) && (_MSC_VER >= 1020)
  14. if (messageBox)
  15. {
  16. MessageBoxA(NULL, msg, "Debug message", MB_OK | MB_ICONASTERISK);
  17. }
  18. # endif
  19. std::cout << msg << std::endl;
  20. #endif
  21. #endif
  22. }
  23. CGeniusAI::CGeniusAI()
  24. : m_generalAI(), turn(0), m_state(NO_BATTLE), firstTurn(true)
  25. {
  26. }
  27. CGeniusAI::~CGeniusAI()
  28. {
  29. }
  30. void CGeniusAI::init(ICallback *CB)
  31. {
  32. m_cb = CB;
  33. m_generalAI.init(CB);
  34. human = false;
  35. playerID = m_cb->getMyColor();
  36. serialID = m_cb->getMySerial();
  37. std::string info = std::string("GeniusAI initialized for player ") + boost::lexical_cast<std::string>(playerID);
  38. m_battleLogic = NULL;
  39. DbgBox(info.c_str());
  40. }
  41. unsigned long randomFromInt(unsigned long in)
  42. {
  43. return (in*214013+2531011);
  44. }
  45. void CGeniusAI::reportResources()
  46. {
  47. std::cout << "AI Player " <<m_cb->getMySerial()<< " with " << m_cb->howManyHeroes(true) << " heroes. " << std::endl;
  48. std::cout << m_cb->getResourceAmount(0) << " wood. ";
  49. std::cout << m_cb->getResourceAmount(1) << " mercury. ";
  50. std::cout << m_cb->getResourceAmount(2) << " ore. ";
  51. std::cout << m_cb->getResourceAmount(3) << " sulfer. ";
  52. std::cout << m_cb->getResourceAmount(4) << " cristal. ";
  53. std::cout << m_cb->getResourceAmount(5) << " gems. ";
  54. std::cout << m_cb->getResourceAmount(6) << " gold.";
  55. std::cout << std::endl;
  56. }
  57. void CGeniusAI::addHeroObjectives(CGeniusAI::HypotheticalGameState::HeroModel &h, CGeniusAI::HypotheticalGameState &hgs)
  58. {
  59. int3 hpos, destination;
  60. CPath path;
  61. hpos = h.pos;
  62. int movement = h.remainingMovement;
  63. for(std::set<AIObjectContainer>::const_iterator i = hgs.knownVisitableObjects.begin(); i != hgs.knownVisitableObjects.end();i++)
  64. {
  65. if(i->o->ID==54||i->o->ID==34) //creatures, another hero
  66. continue;
  67. if(i->o->getOwner()==m_cb->getMyColor())
  68. continue;
  69. destination = i->o->getSightCenter();
  70. if(hpos.z==destination.z)
  71. if(m_cb->getPath(hpos,destination,h.h,path))
  72. {
  73. path.convert(0);
  74. if(path.nodes[0].dist<movement)
  75. {
  76. AIObjective::Type tp = AIObjective::visit;
  77. HeroObjective ho(tp,i->o,&h);
  78. std::set<HeroObjective>::iterator found = currentHeroObjectives.find(ho);
  79. if(found==currentHeroObjectives.end())
  80. currentHeroObjectives.insert(ho);
  81. else
  82. found->whoCanAchieve.push_back(&h);
  83. }
  84. }
  85. }
  86. }
  87. void CGeniusAI::addTownObjectives(HypotheticalGameState::TownModel &t, HypotheticalGameState & hgs)
  88. {
  89. //recruitHero
  90. //recruitCreatures
  91. //upgradeCreatures
  92. //buildBuilding
  93. if(hgs.heroModels.size()<3) //recruitHero
  94. {
  95. if(!t.visitingHero)
  96. {
  97. for(int i =0; i < hgs.AvailableHeroesToBuy.size();i++)
  98. if(hgs.AvailableHeroesToBuy[i]->army.slots.size()>1)//only buy heros with units
  99. {
  100. TownObjective to(AIObjective::recruitHero,&t,0);
  101. currentTownObjectives.insert(to);
  102. }
  103. }
  104. }
  105. // for(int i = 0; i < t.t->creatures.size() ;i++)
  106. // {
  107. // int ID = t.t->creatures[i].second.back();
  108. // CCreature
  109. // cout << "town has " << t.t->creatures[i].first << " level " << i+1 << " " << creature->namePl << endl;
  110. // }
  111. }
  112. void CGeniusAI::TownObjective::fulfill(CGeniusAI & cg, HypotheticalGameState & hgs)
  113. {
  114. switch(type)
  115. {
  116. case recruitHero:
  117. cg.m_cb->recruitHero(whichTown->t,hgs.AvailableHeroesToBuy[which]);
  118. hgs.heroModels.push_back(hgs.AvailableHeroesToBuy[which]);
  119. whichTown->visitingHero = true;
  120. //TODO: sub 2500 gold from hgs here
  121. }
  122. }
  123. void CGeniusAI::getObjectives(CGeniusAI::HypotheticalGameState & hgs)
  124. {
  125. currentHeroObjectives.clear();
  126. currentTownObjectives.clear();
  127. for(std::vector <CGeniusAI::HypotheticalGameState::HeroModel>::iterator i = hgs.heroModels.begin(); i != hgs.heroModels.end(); i++)
  128. addHeroObjectives(*i,hgs);
  129. for(std::vector <CGeniusAI::HypotheticalGameState::TownModel>::iterator i = hgs.townModels.begin(); i != hgs.townModels.end(); i++)
  130. addTownObjectives(*i,hgs);
  131. }
  132. void CGeniusAI::HeroObjective::fulfill(CGeniusAI & cg, HypotheticalGameState & hgs)
  133. {
  134. switch(type)
  135. {
  136. case visit:
  137. HypotheticalGameState::HeroModel * h = whoCanAchieve[rand()%whoCanAchieve.size()];
  138. int3 hpos, destination;
  139. CPath path;
  140. hpos = h->pos;
  141. //std::cout << "trying to visit " << object->hoverName << std::endl;
  142. destination = object->getSightCenter();
  143. if(cg.m_cb->getPath(hpos,destination,h->h,path))
  144. {
  145. path.convert(0);
  146. for(int i = path.nodes.size()-2;i>=0;i--)
  147. cg.m_cb->moveHero(h->h,path.nodes[i].coord);
  148. h->remainingMovement-=path.nodes[0].dist;
  149. if(object->blockVisit)
  150. h->pos = path.nodes[1].coord;
  151. else
  152. h->pos=destination;
  153. std::set<AIObjectContainer>::iterator i = hgs.knownVisitableObjects.find(AIObjectContainer(object));
  154. if(i!=hgs.knownVisitableObjects.end())
  155. hgs.knownVisitableObjects.erase(i);
  156. }
  157. }
  158. }
  159. void CGeniusAI::yourTurn()
  160. {
  161. static int seed = rand();
  162. srand(seed);
  163. if(firstTurn)
  164. {
  165. //m_cb->sendMessage("vcmieagles");
  166. firstTurn = false;
  167. }
  168. knownVisitableObjects.clear();
  169. int3 pos = m_cb->getMapSize();
  170. for(int x = 0;x<pos.x;x++)
  171. for(int y = 0;y<pos.y;y++)
  172. for(int z = 0;z<pos.z;z++)
  173. tileRevealed(int3(x,y,z));
  174. reportResources();
  175. turn++;
  176. HypotheticalGameState hgs(*this);
  177. getObjectives(hgs);
  178. vector<AIObjectivePtrCont> AIObjectiveQueue;
  179. do{
  180. //std::cout << "I have " << currentHeroObjectives.size() << " things I could do with my heroes!" << std::endl;
  181. //std::cout << "I have " << currentTownObjectives.size() << " things I could do with my towns!" << std::endl;
  182. AIObjectiveQueue.clear();
  183. for(std::set<CGeniusAI::HeroObjective>::iterator i = currentHeroObjectives.begin(); i != currentHeroObjectives.end(); i++)
  184. AIObjectiveQueue.push_back(AIObjectivePtrCont(&(*i)));
  185. for(std::set<CGeniusAI::TownObjective>::iterator i = currentTownObjectives.begin(); i != currentTownObjectives.end(); i++)
  186. AIObjectiveQueue.push_back(AIObjectivePtrCont(&(*i)));
  187. if(!AIObjectiveQueue.empty())
  188. max_element(AIObjectiveQueue.begin(),AIObjectiveQueue.end())->obj->fulfill(*this, hgs);
  189. getObjectives(hgs);
  190. }while(!currentHeroObjectives.empty());
  191. seed = rand();
  192. m_cb->endTurn();
  193. }
  194. void CGeniusAI::heroKilled(const CGHeroInstance * hero)
  195. {
  196. }
  197. void CGeniusAI::heroCreated(const CGHeroInstance *hero)
  198. {
  199. }
  200. void CGeniusAI::tileRevealed(int3 pos)
  201. {
  202. std::vector < const CGObjectInstance * > objects = m_cb->getVisitableObjs(pos);
  203. for(std::vector < const CGObjectInstance * >::iterator o = objects.begin();o!=objects.end();o++)
  204. knownVisitableObjects.insert(*o);
  205. objects = m_cb->getFlaggableObjects(pos);
  206. for(std::vector < const CGObjectInstance * >::iterator o = objects.begin();o!=objects.end();o++)
  207. knownVisitableObjects.insert(*o);
  208. }
  209. void CGeniusAI::tileHidden(int3 pos)
  210. {
  211. }
  212. void CGeniusAI::heroMoved(const TryMoveHero &TMH)
  213. {
  214. DbgBox("** CGeniusAI::heroMoved **");
  215. }
  216. void CGeniusAI::heroGotLevel(const CGHeroInstance *hero, int pskill, std::vector<ui16> &skills, boost::function<void(ui32)> &callback)
  217. {
  218. callback(rand() % skills.size());
  219. }
  220. void GeniusAI::CGeniusAI::showGarrisonDialog( const CArmedInstance *up, const CGHeroInstance *down, boost::function<void()> &onEnd )
  221. {
  222. onEnd();
  223. }
  224. void GeniusAI::CGeniusAI::playerBlocked( int reason )
  225. {
  226. if(reason == 0) //battle is coming...
  227. {
  228. m_state.setn(UPCOMING_BATTLE);
  229. }
  230. }
  231. void GeniusAI::CGeniusAI::battleResultsApplied()
  232. {
  233. assert(m_state.get() == ENDING_BATTLE);
  234. m_state.setn(NO_BATTLE);
  235. }
  236. void CGeniusAI::showBlockingDialog(const std::string &text, const std::vector<Component> &components, ui32 askID, const int soundID, bool selection, bool cancel)
  237. {
  238. m_cb->selectionMade(cancel ? 0 : 1, askID);
  239. }
  240. /**
  241. * occurs AFTER every action taken by any stack or by the hero
  242. */
  243. void CGeniusAI::actionFinished(const BattleAction *action)
  244. {
  245. std::string message("\t\tCGeniusAI::actionFinished - type(");
  246. message += boost::lexical_cast<std::string>((unsigned)action->actionType);
  247. message += "), side(";
  248. message += boost::lexical_cast<std::string>((unsigned)action->side);
  249. message += ")";
  250. DbgBox(message.c_str());
  251. }
  252. /**
  253. * occurs BEFORE every action taken by any stack or by the hero
  254. */
  255. void CGeniusAI::actionStarted(const BattleAction *action)
  256. {
  257. std::string message("\t\tCGeniusAI::actionStarted - type(");
  258. message += boost::lexical_cast<std::string>((unsigned)action->actionType);
  259. message += "), side(";
  260. message += boost::lexical_cast<std::string>((unsigned)action->side);
  261. message += ")";
  262. DbgBox(message.c_str());
  263. }
  264. /**
  265. * called when stack is performing attack
  266. */
  267. void CGeniusAI::battleAttack(BattleAttack *ba)
  268. {
  269. DbgBox("\t\t\tCGeniusAI::battleAttack");
  270. }
  271. /**
  272. * called when stack receives damage (after battleAttack())
  273. */
  274. void CGeniusAI::battleStacksAttacked(std::set<BattleStackAttacked> & bsa)
  275. {
  276. DbgBox("\t\t\tCGeniusAI::battleStacksAttacked");
  277. }
  278. /**
  279. * called by engine when battle starts; side=0 - left, side=1 - right
  280. */
  281. void CGeniusAI::battleStart(CCreatureSet *army1, CCreatureSet *army2, int3 tile, CGHeroInstance *hero1, CGHeroInstance *hero2, bool side)
  282. {
  283. assert(!m_battleLogic);
  284. assert(playerID > PLAYER_LIMIT || m_state.get() == UPCOMING_BATTLE); //we have been informed that battle will start (or we are neutral AI)
  285. m_state.setn(ONGOING_BATTLE);
  286. m_battleLogic = new BattleAI::CBattleLogic(m_cb, army1, army2, tile, hero1, hero2, side);
  287. DbgBox("** CGeniusAI::battleStart **");
  288. }
  289. /**
  290. *
  291. */
  292. void CGeniusAI::battleEnd(BattleResult *br)
  293. {
  294. /*switch(br->winner)
  295. {
  296. case 0: std::cout << "The winner is the attacker." << std::endl;break;
  297. case 1: std::cout << "The winner is the defender." << std::endl;break;
  298. case 2: std::cout << "It's a draw." << std::endl;break;
  299. };*/
  300. delete m_battleLogic;
  301. m_battleLogic = NULL;
  302. assert(m_state.get() == ONGOING_BATTLE);
  303. m_state.setn(ENDING_BATTLE);
  304. DbgBox("** CGeniusAI::battleEnd **");
  305. }
  306. /**
  307. * called at the beggining of each turn, round=-1 is the tactic phase, round=0 is the first "normal" turn
  308. */
  309. void CGeniusAI::battleNewRound(int round)
  310. {
  311. std::string message("\tCGeniusAI::battleNewRound - ");
  312. message += boost::lexical_cast<std::string>(round);
  313. DbgBox(message.c_str());
  314. m_battleLogic->SetCurrentTurn(round);
  315. }
  316. /**
  317. *
  318. */
  319. void CGeniusAI::battleStackMoved(int ID, int dest, int distance, bool end)
  320. {
  321. std::string message("\t\t\tCGeniusAI::battleStackMoved ID(");
  322. message += boost::lexical_cast<std::string>(ID);
  323. message += "), dest(";
  324. message += boost::lexical_cast<std::string>(dest);
  325. message += ")";
  326. DbgBox(message.c_str());
  327. }
  328. /**
  329. *
  330. */
  331. void CGeniusAI::battleSpellCast(SpellCast *sc)
  332. {
  333. DbgBox("\t\t\tCGeniusAI::battleSpellCast");
  334. }
  335. /**
  336. * called when battlefield is prepared, prior the battle beginning
  337. */
  338. void CGeniusAI::battlefieldPrepared(int battlefieldType, std::vector<CObstacle*> obstacles)
  339. {
  340. DbgBox("CGeniusAI::battlefieldPrepared");
  341. }
  342. /**
  343. *
  344. */
  345. void CGeniusAI::battleStackMoved(int ID, int dest, bool startMoving, bool endMoving)
  346. {
  347. DbgBox("\t\t\tCGeniusAI::battleStackMoved");
  348. }
  349. /**
  350. *
  351. */
  352. void CGeniusAI::battleStackAttacking(int ID, int dest)
  353. {
  354. DbgBox("\t\t\tCGeniusAI::battleStackAttacking");
  355. }
  356. /**
  357. *
  358. */
  359. void CGeniusAI::battleStackIsAttacked(int ID, int dmg, int killed, int IDby, bool byShooting)
  360. {
  361. DbgBox("\t\t\tCGeniusAI::battleStackIsAttacked");
  362. }
  363. /**
  364. * called when it's turn of that stack
  365. */
  366. BattleAction CGeniusAI::activeStack(int stackID)
  367. {
  368. std::string message("\t\t\tCGeniusAI::activeStack stackID(");
  369. message += boost::lexical_cast<std::string>(stackID);
  370. message += ")";
  371. DbgBox(message.c_str());
  372. return m_battleLogic->MakeDecision(stackID);
  373. };