CGeniusAI.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092
  1. #include "CGeniusAI.h"
  2. #include <iostream>
  3. #include <fstream>
  4. #include <math.h>
  5. #include <boost/lexical_cast.hpp>
  6. #include <boost/lambda/lambda.hpp>
  7. #include <boost/lambda/bind.hpp>
  8. #include <boost/lambda/if.hpp>
  9. #include <boost/algorithm/string/split.hpp>
  10. #include <boost/algorithm/string/classification.hpp>
  11. #include <boost/algorithm/string.hpp>
  12. using namespace boost::lambda;
  13. using namespace std;
  14. using namespace GeniusAI;
  15. #if defined (_MSC_VER) && (_MSC_VER >= 1020) || (__MINGW32__)
  16. #include <windows.h>
  17. #endif
  18. void MsgBox(const char *msg, bool messageBox = false)
  19. {
  20. #if defined _DEBUG
  21. # if defined (_MSC_VER) && (_MSC_VER >= 1020)
  22. if (messageBox)
  23. {
  24. MessageBoxA(NULL, msg, "Debug message", MB_OK | MB_ICONASTERISK);
  25. }
  26. # endif
  27. std::cout << msg << std::endl;
  28. #endif
  29. }
  30. void CGeniusAI::init(ICallback *CB)
  31. {
  32. m_cb = CB;
  33. human = false;
  34. playerID = m_cb->getMyColor();
  35. serialID = m_cb->getMySerial();
  36. std::string info = std::string("GeniusAI initialized for player ") + boost::lexical_cast<std::string>(playerID);
  37. m_battleLogic = NULL;
  38. MsgBox(info.c_str());
  39. }
  40. void CGeniusAI::yourTurn()
  41. {
  42. m_cb->endTurn();
  43. }
  44. void CGeniusAI::heroKilled(const CGHeroInstance *)
  45. {
  46. }
  47. void CGeniusAI::heroCreated(const CGHeroInstance *)
  48. {
  49. }
  50. void CGeniusAI::heroMoved(const HeroMoveDetails &)
  51. {
  52. }
  53. void CGeniusAI::heroGotLevel(const CGHeroInstance *hero, int pskill, std::vector<ui16> &skills, boost::function<void(ui32)> &callback)
  54. {
  55. callback(rand() % skills.size());
  56. }
  57. /**
  58. * occurs AFTER every action taken by any stack or by the hero
  59. */
  60. void CGeniusAI::actionFinished(const BattleAction *action)
  61. {
  62. std::string message("\t\tCGeniusAI::actionFinished - type(");
  63. message += boost::lexical_cast<std::string>((unsigned)action->actionType);
  64. message += "), side(";
  65. message += boost::lexical_cast<std::string>((unsigned)action->side);
  66. message += ")";
  67. MsgBox(message.c_str());
  68. }
  69. /**
  70. * occurs BEFORE every action taken by any stack or by the hero
  71. */
  72. void CGeniusAI::actionStarted(const BattleAction *action)
  73. {
  74. std::string message("\t\tCGeniusAI::actionStarted - type(");
  75. message += boost::lexical_cast<std::string>((unsigned)action->actionType);
  76. message += "), side(";
  77. message += boost::lexical_cast<std::string>((unsigned)action->side);
  78. message += ")";
  79. MsgBox(message.c_str());
  80. }
  81. /**
  82. * called when stack is performing attack
  83. */
  84. void CGeniusAI::battleAttack(BattleAttack *ba)
  85. {
  86. MsgBox("\t\t\tCGeniusAI::battleAttack");
  87. }
  88. /**
  89. * called when stack receives damage (after battleAttack())
  90. */
  91. void CGeniusAI::battleStacksAttacked(std::set<BattleStackAttacked> & bsa)
  92. {
  93. MsgBox("\t\t\tCGeniusAI::battleStacksAttacked");
  94. }
  95. /**
  96. * called by engine when battle starts; side=0 - left, side=1 - right
  97. */
  98. void CGeniusAI::battleStart(CCreatureSet *army1, CCreatureSet *army2, int3 tile, CGHeroInstance *hero1, CGHeroInstance *hero2, bool side)
  99. {
  100. assert(!m_battleLogic);
  101. m_battleLogic = new CBattleLogic(m_cb, army1, army2, tile, hero1, hero2, side);
  102. assert(m_battleLogic);
  103. MsgBox("** CGeniusAI::battleStart **");
  104. }
  105. /**
  106. *
  107. */
  108. void CGeniusAI::battleEnd(BattleResult *br)
  109. {
  110. delete m_battleLogic;
  111. m_battleLogic = NULL;
  112. MsgBox("** CGeniusAI::battleEnd **");
  113. }
  114. /**
  115. * called at the beggining of each turn, round=-1 is the tactic phase, round=0 is the first "normal" turn
  116. */
  117. void CGeniusAI::battleNewRound(int round)
  118. {
  119. std::string message("\tCGeniusAI::battleNewRound - ");
  120. message += boost::lexical_cast<std::string>(round);
  121. MsgBox(message.c_str());
  122. m_battleLogic->SetCurrentTurn(round);
  123. }
  124. /**
  125. *
  126. */
  127. void CGeniusAI::battleStackMoved(int ID, int dest, int distance, bool end)
  128. {
  129. std::string message("\t\t\tCGeniusAI::battleStackMoved ID(");
  130. message += boost::lexical_cast<std::string>(ID);
  131. message += "), dest(";
  132. message += boost::lexical_cast<std::string>(dest);
  133. message += ")";
  134. MsgBox(message.c_str());
  135. }
  136. /**
  137. *
  138. */
  139. void CGeniusAI::battleSpellCasted(SpellCasted *sc)
  140. {
  141. MsgBox("\t\t\tCGeniusAI::battleSpellCasted");
  142. }
  143. /**
  144. * called when battlefield is prepared, prior the battle beginning
  145. */
  146. void CGeniusAI::battlefieldPrepared(int battlefieldType, std::vector<CObstacle*> obstacles)
  147. {
  148. MsgBox("CGeniusAI::battlefieldPrepared");
  149. }
  150. /**
  151. *
  152. */
  153. void CGeniusAI::battleStackMoved(int ID, int dest, bool startMoving, bool endMoving)
  154. {
  155. MsgBox("\t\t\tCGeniusAI::battleStackMoved");
  156. }
  157. /**
  158. *
  159. */
  160. void CGeniusAI::battleStackAttacking(int ID, int dest)
  161. {
  162. MsgBox("\t\t\tCGeniusAI::battleStackAttacking");
  163. }
  164. /**
  165. *
  166. */
  167. void CGeniusAI::battleStackIsAttacked(int ID, int dmg, int killed, int IDby, bool byShooting)
  168. {
  169. MsgBox("\t\t\tCGeniusAI::battleStackIsAttacked");
  170. }
  171. /**
  172. * called when it's turn of that stack
  173. */
  174. BattleAction CGeniusAI::activeStack(int stackID)
  175. {
  176. std::string message("\t\t\tCGeniusAI::activeStack stackID(");
  177. message += boost::lexical_cast<std::string>(stackID);
  178. message += ")";
  179. MsgBox(message.c_str());
  180. return m_battleLogic->MakeDecision(stackID);
  181. };
  182. /*
  183. ui8 side; //who made this action: false - left, true - right player
  184. ui32 stackNumber;//stack ID, -1 left hero, -2 right hero,
  185. ui8 actionType; //
  186. 0 = Cancel BattleAction
  187. 1 = Hero cast a spell
  188. 2 = Walk
  189. 3 = Defend
  190. 4 = Retreat from the battle
  191. 5 = Surrender
  192. 6 = Walk and Attack
  193. 7 = Shoot
  194. 8 = Wait
  195. 9 = Catapult
  196. 10 = Monster casts a spell (i.e. Faerie Dragons)
  197. ui16 destinationTile;
  198. si32 additionalInfo; // e.g. spell number if type is 1 || 10; tile to attack if type is 6
  199. */
  200. /**
  201. * Implementation of CBattleHelper class.
  202. */
  203. CBattleHelper::CBattleHelper():
  204. InfiniteDistance(0xffff),
  205. BattlefieldHeight(11),
  206. BattlefieldWidth(15),
  207. m_voteForDistance(10),
  208. m_voteForDistanceFromShooters(20),
  209. m_voteForHitPoints(10),
  210. m_voteForMaxDamage(10),
  211. m_voteForMaxSpeed(10),
  212. m_voteForMinDamage(10)
  213. {
  214. // loads votes
  215. std::fstream f;
  216. f.open("AI\\CBattleHelper.txt", std::ios::in);
  217. if (f)
  218. {
  219. //char c_line[512];
  220. std::string line;
  221. while (std::getline(f, line, '\n'))
  222. {
  223. //f.getline(c_line, sizeof(c_line), '\n');
  224. //std::string line(c_line);
  225. //std::getline(f, line);
  226. std::vector<std::string> parts;
  227. boost::algorithm::split(parts, line, boost::algorithm::is_any_of("="));
  228. if (parts.size() >= 2)
  229. {
  230. boost::algorithm::trim(parts[0]);
  231. boost::algorithm::trim(parts[1]);
  232. if (parts[0].compare("m_voteForDistance") == 0)
  233. {
  234. try
  235. {
  236. m_voteForDistance = boost::lexical_cast<int>(parts[1]);
  237. }
  238. catch (boost::bad_lexical_cast &)
  239. {}
  240. }
  241. else if (parts[0].compare("m_voteForDistanceFromShooters") == 0)
  242. {
  243. try
  244. {
  245. m_voteForDistanceFromShooters = boost::lexical_cast<int>(parts[1]);
  246. }
  247. catch (boost::bad_lexical_cast &)
  248. {}
  249. }
  250. else if (parts[0].compare("m_voteForHitPoints") == 0)
  251. {
  252. try
  253. {
  254. m_voteForHitPoints = boost::lexical_cast<int>(parts[1]);
  255. }
  256. catch (boost::bad_lexical_cast &)
  257. {}
  258. }
  259. else if (parts[0].compare("m_voteForMaxDamage") == 0)
  260. {
  261. try
  262. {
  263. m_voteForMaxDamage = boost::lexical_cast<int>(parts[1]);
  264. }
  265. catch (boost::bad_lexical_cast &)
  266. {}
  267. }
  268. else if (parts[0].compare("m_voteForMaxSpeed") == 0)
  269. {
  270. try
  271. {
  272. m_voteForMaxSpeed = boost::lexical_cast<int>(parts[1]);
  273. }
  274. catch (boost::bad_lexical_cast &)
  275. {}
  276. }
  277. else if (parts[0].compare("m_voteForMinDamage") == 0)
  278. {
  279. try
  280. {
  281. m_voteForMinDamage = boost::lexical_cast<int>(parts[1]);
  282. }
  283. catch (boost::bad_lexical_cast &)
  284. {}
  285. }
  286. }
  287. }
  288. f.close();
  289. }
  290. }
  291. CBattleHelper::~CBattleHelper()
  292. {}
  293. int CBattleHelper::GetBattleFieldPosition(int x, int y)
  294. {
  295. return x + 17 * (y - 1);
  296. }
  297. int CBattleHelper::DecodeXPosition(int battleFieldPosition)
  298. {
  299. int pos = battleFieldPosition - (DecodeYPosition(battleFieldPosition) - 1) * 17;
  300. assert(pos > 0 && pos < 16);
  301. return pos;
  302. }
  303. int CBattleHelper::DecodeYPosition(int battleFieldPosition)
  304. {
  305. double y = (double)battleFieldPosition / 17.0;
  306. if (y - (int)y > 0.0)
  307. {
  308. return (int)y + 1;
  309. }
  310. assert((int)y > 0 && (int)y <= 11);
  311. return (int)y;
  312. }
  313. int CBattleHelper::GetShortestDistance(int pointA, int pointB)
  314. {
  315. /**
  316. * TODO: function hasn't been checked!
  317. */
  318. int x1 = DecodeXPosition(pointA);
  319. int y1 = DecodeYPosition(pointA);
  320. //
  321. int x2 = DecodeXPosition(pointB);
  322. //x2 += (x2 % 2)? 0 : 1;
  323. int y2 = DecodeYPosition(pointB);
  324. //
  325. double dx = x1 - x2;
  326. double dy = y1 - y2;
  327. return (int)sqrt(dx * dx + dy * dy);
  328. }
  329. int CBattleHelper::GetDistanceWithObstacles(int pointA, int pointB)
  330. {
  331. // TODO - implement this!
  332. return GetShortestDistance(pointA, pointB);
  333. }
  334. /**
  335. * Implementation of CBattleLogic class.
  336. */
  337. CBattleLogic::CBattleLogic(ICallback *cb, CCreatureSet *army1, CCreatureSet *army2, int3 tile, CGHeroInstance *hero1, CGHeroInstance *hero2, bool side) :
  338. m_cb(cb),
  339. m_iCurrentTurn(-2),
  340. m_bIsAttacker(false),
  341. m_army1(army1),
  342. m_army2(army2),
  343. m_tile(tile),
  344. m_hero1(hero1),
  345. m_hero2(hero2),
  346. m_side(side)
  347. {
  348. const int max_enemy_creatures = 12;
  349. m_statMaxDamage.reserve(max_enemy_creatures);
  350. m_statMinDamage.reserve(max_enemy_creatures);
  351. m_statMaxSpeed.reserve(max_enemy_creatures);
  352. m_statDistance.reserve(max_enemy_creatures);
  353. m_statDistanceFromShooters.reserve(max_enemy_creatures);
  354. m_statHitPoints.reserve(max_enemy_creatures);
  355. }
  356. CBattleLogic::~CBattleLogic()
  357. {}
  358. void CBattleLogic::SetCurrentTurn(int turn)
  359. {
  360. m_iCurrentTurn = turn;
  361. }
  362. void CBattleLogic::MakeStatistics(int currentCreatureId)
  363. {
  364. typedef std::map<int, CStack> map_stacks;
  365. map_stacks allStacks = m_cb->battleGetStacks();
  366. const CStack *currentStack = m_cb->battleGetStackByID(currentCreatureId);
  367. /*
  368. // find all creatures belong to the enemy
  369. std::for_each(allStacks.begin(), allStacks.end(),
  370. if_(bind<ui8>(&CStack::attackerOwned, bind<CStack>(&map_stacks::value_type::second, _1)) == m_bIsAttacker)
  371. [
  372. var(enemy)[ret<int>(bind<int>(&map_stacks::value_type::first, _1))] =
  373. ret<CStack>(bind<CStack>(&map_stacks::value_type::second, _1))
  374. ]
  375. );
  376. // fill other containers
  377. // max damage
  378. std::for_each(enemy.begin(), enemy.end(),
  379. var(m_statMaxDamage)[ret<int>(bind<int>(&map_stacks::value_type::first, _1))] =
  380. ret<int>(bind<int>(&CCreature::damageMax, bind<CCreature*>(&CStack::creature,
  381. bind<CStack>(&map_stacks::value_type::second, _1))))
  382. );
  383. // min damage
  384. std::for_each(enemy.begin(), enemy.end(),
  385. var(m_statMinDamage)[ret<int>(bind<int>(&map_stacks::value_type::first, _1))] =
  386. ret<int>(bind<int>(&CCreature::damageMax, bind<CCreature*>(&CStack::creature,
  387. bind<CStack>(&map_stacks::value_type::second, _1))))
  388. );
  389. */
  390. m_statMaxDamage.clear();
  391. m_statMinDamage.clear();
  392. m_statHitPoints.clear();
  393. m_statMaxSpeed.clear();
  394. m_statDistanceFromShooters.clear();
  395. m_statDistance.clear();
  396. m_statDistance.clear();
  397. m_statCasualties.clear();
  398. int totalEnemyDamage = 0;
  399. int totalEnemyHitPoints = 0;
  400. int totalDamage = 0;
  401. int totalHitPoints = 0;
  402. for (map_stacks::const_iterator it = allStacks.begin(); it != allStacks.end(); ++it)
  403. {
  404. const CStack *st = &it->second;
  405. if ((it->second.attackerOwned != 0) != m_bIsAttacker)
  406. {
  407. int id = it->first;
  408. if (st->amount < 1)
  409. {
  410. continue;
  411. }
  412. // make stats
  413. int hitPoints = st->amount * st->creature->hitPoints - (st->creature->hitPoints - st->firstHPleft);
  414. m_statMaxDamage.push_back(std::pair<int, int>(id, st->creature->damageMax * st->amount));
  415. m_statMinDamage.push_back(std::pair<int, int>(id, st->creature->damageMin * st->amount));
  416. m_statHitPoints.push_back(std::pair<int, int>(id, hitPoints));
  417. m_statMaxSpeed.push_back(std::pair<int, int>(id, st->creature->speed));
  418. totalEnemyDamage += (st->creature->damageMax + st->creature->damageMin) * st->amount / 2;
  419. totalEnemyHitPoints += hitPoints;
  420. // calculate casualties
  421. SCreatureCasualties cs;
  422. // hp * amount - damage * ( (att - def)>=0 )
  423. // hit poionts
  424. assert(hitPoints >= 0 && "CGeniusAI - creature cannot have hit points less than zero");
  425. CGHeroInstance *attackerHero = (m_side)? m_hero1 : m_hero2;
  426. CGHeroInstance *defendingHero = (m_side)? m_hero2 : m_hero1;
  427. int attackDefenseBonus = currentStack->creature->attack + (attackerHero ? attackerHero->getPrimSkillLevel(0) : 0) - (st->creature->defence + (defendingHero ? defendingHero->getPrimSkillLevel(1) : 0));
  428. float damageFactor = 1.0f;
  429. if(attackDefenseBonus < 0) //decreasing dmg
  430. {
  431. if(0.02f * (-attackDefenseBonus) > 0.3f)
  432. {
  433. damageFactor += -0.3f;
  434. }
  435. else
  436. {
  437. damageFactor += 0.02f * attackDefenseBonus;
  438. }
  439. }
  440. else //increasing dmg
  441. {
  442. if(0.05f * attackDefenseBonus > 4.0f)
  443. {
  444. damageFactor += 4.0f;
  445. }
  446. else
  447. {
  448. damageFactor += 0.05f * attackDefenseBonus;
  449. }
  450. }
  451. cs.damage_max = (int)(currentStack->creature->damageMax * currentStack->amount * damageFactor);
  452. if (cs.damage_max > hitPoints)
  453. {
  454. cs.damage_max = hitPoints;
  455. }
  456. cs.damage_min = (int)(currentStack->creature->damageMin * currentStack->amount * damageFactor);
  457. if (cs.damage_min > hitPoints)
  458. {
  459. cs.damage_min = hitPoints;
  460. }
  461. cs.amount_max = cs.damage_max / st->creature->hitPoints;
  462. cs.amount_min = cs.damage_min / st->creature->hitPoints;
  463. cs.leftHitPoints_for_max = (hitPoints - cs.damage_max) % st->creature->hitPoints;
  464. cs.leftHitPoint_for_min = (hitPoints - cs.damage_min) % st->creature->hitPoints;
  465. m_statCasualties.push_back(std::pair<int, SCreatureCasualties>(id, cs));
  466. if (st->creature->isShooting() && st->shots > 0)
  467. {
  468. m_statDistanceFromShooters.push_back(std::pair<int, int>(id, m_battleHelper.GetShortestDistance(currentStack->position, st->position)));
  469. }
  470. if (currentStack->creature->isFlying() || (currentStack->creature->isShooting() && currentStack->shots > 0))
  471. {
  472. m_statDistance.push_back(std::pair<int, int>(id, m_battleHelper.GetShortestDistance(currentStack->position, st->position)));
  473. }
  474. else
  475. {
  476. m_statDistance.push_back(std::pair<int, int>(id, m_battleHelper.GetDistanceWithObstacles(currentStack->position, st->position)));
  477. }
  478. }
  479. else
  480. {
  481. if (st->amount < 1)
  482. {
  483. continue;
  484. }
  485. int hitPoints = st->amount * st->creature->hitPoints - (st->creature->hitPoints - st->firstHPleft);
  486. totalDamage += (st->creature->damageMax + st->creature->damageMin) * st->amount / 2;
  487. totalHitPoints += hitPoints;
  488. }
  489. }
  490. if ((float)totalDamage / (float)totalEnemyDamage < 0.5f &&
  491. (float)totalHitPoints / (float)totalEnemyHitPoints < 0.5f)
  492. {
  493. m_bEnemyDominates = true;
  494. MsgBox("** EnemyDominates!");
  495. }
  496. else
  497. {
  498. m_bEnemyDominates = false;
  499. }
  500. // sort max damage
  501. std::sort(m_statMaxDamage.begin(), m_statMaxDamage.end(),
  502. bind(&creature_stat::value_type::second, _1) > bind(&creature_stat::value_type::second, _2));
  503. // sort min damage
  504. std::sort(m_statMinDamage.begin(), m_statMinDamage.end(),
  505. bind(&creature_stat::value_type::second, _1) > bind(&creature_stat::value_type::second, _2));
  506. // sort max speed
  507. std::sort(m_statMaxSpeed.begin(), m_statMaxSpeed.end(),
  508. bind(&creature_stat::value_type::second, _1) > bind(&creature_stat::value_type::second, _2));
  509. // sort distance
  510. std::sort(m_statDistance.begin(), m_statDistance.end(),
  511. bind(&creature_stat::value_type::second, _1) < bind(&creature_stat::value_type::second, _2));
  512. // sort distance from shooters
  513. std::sort(m_statDistanceFromShooters.begin(), m_statDistanceFromShooters.end(),
  514. bind(&creature_stat::value_type::second, _1) < bind(&creature_stat::value_type::second, _2));
  515. // sort hit points
  516. std::sort(m_statHitPoints.begin(), m_statHitPoints.end(),
  517. bind(&creature_stat::value_type::second, _1) > bind(&creature_stat::value_type::second, _2));
  518. // sort casualties
  519. std::sort(m_statCasualties.begin(), m_statCasualties.end(),
  520. bind(&creature_stat_casualties::value_type::second_type::damage_max, bind(&creature_stat_casualties::value_type::second, _1))
  521. >
  522. bind(&creature_stat_casualties::value_type::second_type::damage_max, bind(&creature_stat_casualties::value_type::second, _2)));
  523. }
  524. BattleAction CBattleLogic::MakeDecision(int stackID)
  525. {
  526. MakeStatistics(stackID);
  527. list<int> creatures;
  528. int additionalInfo;
  529. if (m_bEnemyDominates)
  530. {
  531. creatures = PerformBerserkAttack(stackID, additionalInfo);
  532. }
  533. else
  534. {
  535. creatures = PerformDefaultAction(stackID, additionalInfo);
  536. }
  537. /*
  538. std::string message("Creature will be attacked - ");
  539. message += boost::lexical_cast<std::string>(creature_to_attack);
  540. MsgBox(message.c_str());
  541. */
  542. if (additionalInfo == -1 || creatures.empty())
  543. {
  544. // defend
  545. return MakeDefend(stackID);
  546. }
  547. else if (additionalInfo == -2)
  548. {
  549. return MakeWait(stackID);
  550. }
  551. list<int>::iterator it, eit;
  552. eit = creatures.end();
  553. for (it = creatures.begin(); it != eit; ++it)
  554. {
  555. BattleAction ba = MakeAttack(stackID, *it);
  556. if (ba.actionType != action_walk_and_attack)
  557. {
  558. continue;
  559. }
  560. else
  561. {
  562. PrintBattleAction(ba);
  563. return ba;
  564. }
  565. }
  566. BattleAction ba = MakeAttack(stackID, *creatures.begin());
  567. return ba;
  568. }
  569. std::vector<int> CBattleLogic::GetAvailableHexesForAttacker(CStack *defender, CStack *attacker)
  570. {
  571. int x = m_battleHelper.DecodeXPosition(defender->position);
  572. int y = m_battleHelper.DecodeYPosition(defender->position);
  573. bool defenderIsDW = defender->creature->isDoubleWide();
  574. bool attackerIsDW = attacker->creature->isDoubleWide();
  575. // TOTO: should be std::vector<int> but for debug purpose std::pair is used
  576. typedef std::pair<int, int> hexPoint;
  577. std::list<hexPoint> candidates;
  578. std::vector<int> fields;
  579. if (defenderIsDW)
  580. {
  581. if (defender->attackerOwned)
  582. {
  583. // from left side
  584. if (!(y % 2))
  585. {
  586. // up
  587. candidates.push_back(hexPoint(x - 2, y - 1));
  588. candidates.push_back(hexPoint(x - 1, y - 1));
  589. candidates.push_back(hexPoint(x, y - 1));
  590. // down
  591. candidates.push_back(hexPoint(x - 2, y + 1));
  592. candidates.push_back(hexPoint(x - 1, y + 1));
  593. candidates.push_back(hexPoint(x, y + 1));
  594. }
  595. else
  596. {
  597. // up
  598. candidates.push_back(hexPoint(x - 1, y - 1));
  599. candidates.push_back(hexPoint(x, y - 1));
  600. candidates.push_back(hexPoint(x + 1, y - 1));
  601. // down
  602. candidates.push_back(hexPoint(x - 1, y + 1));
  603. candidates.push_back(hexPoint(x, y + 1));
  604. candidates.push_back(hexPoint(x + 1, y + 1));
  605. }
  606. candidates.push_back(hexPoint(x - 2, y));
  607. candidates.push_back(hexPoint(x + 1, y));
  608. }
  609. else
  610. {
  611. // from right
  612. if (!(y % 2))
  613. {
  614. // up
  615. candidates.push_back(hexPoint(x - 1, y - 1));
  616. candidates.push_back(hexPoint(x, y - 1));
  617. candidates.push_back(hexPoint(x + 1, y - 1));
  618. // down
  619. candidates.push_back(hexPoint(x - 1, y + 1));
  620. candidates.push_back(hexPoint(x, y + 1));
  621. candidates.push_back(hexPoint(x + 1, y + 1));
  622. }
  623. else
  624. {
  625. // up
  626. candidates.push_back(hexPoint(x, y - 1));
  627. candidates.push_back(hexPoint(x + 1, y - 1));
  628. candidates.push_back(hexPoint(x + 2, y - 1));
  629. // down
  630. candidates.push_back(hexPoint(x, y + 1));
  631. candidates.push_back(hexPoint(x + 1, y + 1));
  632. candidates.push_back(hexPoint(x + 2, y + 1));
  633. }
  634. candidates.push_back(hexPoint(x - 1, y));
  635. candidates.push_back(hexPoint(x + 2, y));
  636. }
  637. }
  638. else
  639. {
  640. if (!(y % 2)) // even line
  641. {
  642. // up
  643. candidates.push_back(hexPoint(x - 1, y - 1));
  644. candidates.push_back(hexPoint(x, y - 1));
  645. // down
  646. candidates.push_back(hexPoint(x - 1, y + 1));
  647. candidates.push_back(hexPoint(x, y + 1));
  648. }
  649. else // odd line
  650. {
  651. // up
  652. candidates.push_back(hexPoint(x, y - 1));
  653. candidates.push_back(hexPoint(x + 1, y - 1));
  654. // down
  655. candidates.push_back(hexPoint(x, y + 1));
  656. candidates.push_back(hexPoint(x + 1, y + 1));
  657. }
  658. candidates.push_back(hexPoint(x + 1, y));
  659. candidates.push_back(hexPoint(x - 1, y));
  660. }
  661. // remove fields which are out of bounds or obstacles
  662. for (std::list<hexPoint>::iterator it = candidates.begin(); it != candidates.end(); ++it)
  663. {
  664. if (it->first < 1 || it->first > m_battleHelper.BattlefieldWidth ||
  665. it->second < 1 || it->second > m_battleHelper.BattlefieldHeight)
  666. {
  667. // field is out of bounds
  668. //it = candidates.erase(it);
  669. continue;
  670. }
  671. int new_pos = m_battleHelper.GetBattleFieldPosition(it->first, it->second);
  672. CStack *st = m_cb->battleGetStackByPos(new_pos);
  673. if (st == NULL || st->amount < 1)
  674. {
  675. if (attackerIsDW)
  676. {
  677. int tail_pos = -1;
  678. if (attacker->attackerOwned) // left side
  679. {
  680. int tail_pos_x = it->first - 1;
  681. if (tail_pos_x < 1)
  682. {
  683. continue;
  684. }
  685. tail_pos = m_battleHelper.GetBattleFieldPosition(it->first, it->second);
  686. }
  687. else // right side
  688. {
  689. int tail_pos_x = it->first + 1;
  690. if (tail_pos_x > m_battleHelper.BattlefieldWidth)
  691. {
  692. continue;
  693. }
  694. tail_pos = m_battleHelper.GetBattleFieldPosition(it->first, it->second);
  695. }
  696. assert(tail_pos >= 0 && "Error during calculation position of double wide creature");
  697. CStack *tailStack = m_cb->battleGetStackByPos(tail_pos);
  698. if (st != NULL && st->amount >= 1)
  699. {
  700. continue;
  701. }
  702. }
  703. fields.push_back(new_pos);
  704. }
  705. else if (attacker)
  706. {
  707. if (attacker->ID == st->ID)
  708. {
  709. fields.push_back(new_pos);
  710. }
  711. }
  712. //
  713. //++it;
  714. }
  715. return fields;
  716. }
  717. BattleAction CBattleLogic::MakeDefend(int stackID)
  718. {
  719. BattleAction ba;
  720. ba.side = 1;
  721. ba.actionType = action_defend;
  722. ba.stackNumber = stackID;
  723. ba.additionalInfo = -1;
  724. return ba;
  725. }
  726. BattleAction CBattleLogic::MakeWait(int stackID)
  727. {
  728. BattleAction ba;
  729. ba.side = 1;
  730. ba.actionType = action_wait;
  731. ba.stackNumber = stackID;
  732. ba.additionalInfo = -1;
  733. return ba;
  734. }
  735. BattleAction CBattleLogic::MakeAttack(int attackerID, int destinationID)
  736. {
  737. if (m_cb->battleCanShoot(attackerID, m_cb->battleGetPos(destinationID)))
  738. {
  739. // shoot
  740. BattleAction ba;
  741. ba.side = 1;
  742. ba.additionalInfo = -1;
  743. ba.actionType = action_shoot; // shoot
  744. ba.stackNumber = attackerID;
  745. ba.destinationTile = (ui16)m_cb->battleGetPos(destinationID);
  746. return ba;
  747. }
  748. else
  749. {
  750. // go or go&attack
  751. int dest_tile = -1;
  752. std::vector<int> av_tiles = GetAvailableHexesForAttacker(m_cb->battleGetStackByID(destinationID), m_cb->battleGetStackByID(attackerID));
  753. if (av_tiles.size() < 1)
  754. {
  755. return MakeDefend(attackerID);
  756. }
  757. // get the best tile - now the nearest
  758. int prev_distance = m_battleHelper.InfiniteDistance;
  759. int currentPos = m_cb->battleGetPos(attackerID);
  760. for (std::vector<int>::iterator it = av_tiles.begin(); it != av_tiles.end(); ++it)
  761. {
  762. int dist = m_battleHelper.GetDistanceWithObstacles(*it, m_cb->battleGetPos(attackerID));
  763. if (dist < prev_distance)
  764. {
  765. prev_distance = dist;
  766. dest_tile = *it;
  767. }
  768. if (*it == currentPos)
  769. {
  770. dest_tile = currentPos;
  771. break;
  772. }
  773. }
  774. std::vector<int> fields = m_cb->battleGetAvailableHexes(attackerID, false);
  775. if(fields.size() == 0)
  776. {
  777. return MakeDefend(attackerID);
  778. }
  779. BattleAction ba;
  780. ba.side = 1;
  781. //ba.actionType = 6; // go and attack
  782. ba.stackNumber = attackerID;
  783. ba.destinationTile = (ui16)dest_tile;
  784. //simplified checking for possibility of attack (previous was too simplified)
  785. int destStackPos = m_cb->battleGetPos(destinationID);
  786. if(BattleInfo::mutualPosition(dest_tile, destStackPos) != -1)
  787. ba.additionalInfo = destStackPos;
  788. else if(BattleInfo::mutualPosition(dest_tile, destStackPos+1) != -1)
  789. ba.additionalInfo = destStackPos+1;
  790. else if(BattleInfo::mutualPosition(dest_tile, destStackPos-1) != -1)
  791. ba.additionalInfo = destStackPos-1;
  792. else
  793. MakeDefend(attackerID);
  794. int nearest_dist = m_battleHelper.InfiniteDistance;
  795. int nearest_pos = -1;
  796. // if double wide calculate tail
  797. CStack *attackerStack = m_cb->battleGetStackByID(attackerID);
  798. assert(attackerStack != NULL);
  799. int tail_pos = -1;
  800. if (attackerStack->creature->isDoubleWide())
  801. {
  802. int x_pos = m_battleHelper.DecodeXPosition(attackerStack->position);
  803. int y_pos = m_battleHelper.DecodeYPosition(attackerStack->position);
  804. if (attackerStack->attackerOwned)
  805. {
  806. x_pos -= 1;
  807. }
  808. else
  809. {
  810. x_pos += 1;
  811. }
  812. // if creature can perform attack without movement - do it!
  813. tail_pos = m_battleHelper.GetBattleFieldPosition(x_pos, y_pos);
  814. if (dest_tile == tail_pos)
  815. {
  816. ba.additionalInfo = dest_tile;
  817. ba.actionType = action_walk_and_attack;
  818. PrintBattleAction(ba);
  819. return ba;
  820. }
  821. }
  822. for (std::vector<int>::const_iterator it = fields.begin(); it != fields.end(); ++it)
  823. {
  824. if (*it == dest_tile)
  825. {
  826. // attack!
  827. ba.actionType = action_walk_and_attack;
  828. #if defined _DEBUG
  829. PrintBattleAction(ba);
  830. #endif
  831. return ba;
  832. }
  833. int d = m_battleHelper.GetDistanceWithObstacles(dest_tile, *it);
  834. if (d < nearest_dist)
  835. {
  836. nearest_dist = d;
  837. nearest_pos = *it;
  838. }
  839. }
  840. string message;
  841. message = "Attacker position X=";
  842. message += boost::lexical_cast<std::string>(m_battleHelper.DecodeXPosition(nearest_pos)) + ", Y=";
  843. message += boost::lexical_cast<std::string>(m_battleHelper.DecodeYPosition(nearest_pos));
  844. MsgBox(message.c_str());
  845. ba.actionType = action_walk;
  846. ba.destinationTile = (ui16)nearest_pos;
  847. ba.additionalInfo = -1;
  848. #if defined _DEBUG
  849. PrintBattleAction(ba);
  850. #endif
  851. return ba;
  852. }
  853. }
  854. /**
  855. * The main idea is to perform maximum casualties.
  856. */
  857. list<int> CBattleLogic::PerformBerserkAttack(int stackID, int &additionalInfo)
  858. {
  859. CCreature c = m_cb->battleGetCreature(stackID);
  860. // attack to make biggest damage
  861. list<int> creatures;
  862. if (!m_statCasualties.empty())
  863. {
  864. //creature_to_attack = m_statCasualties.begin()->first;
  865. creature_stat_casualties::iterator it = m_statCasualties.begin();
  866. for (; it != m_statCasualties.end(); ++it)
  867. {
  868. if (it->second.amount_min <= 0)
  869. {
  870. creatures.push_back(it->first);
  871. continue;
  872. }
  873. for (creature_stat::const_iterator it2 = m_statDistance.begin(); it2 != m_statDistance.end(); ++it2)
  874. {
  875. if (it2->first == it->first && it2->second - 1 <= c.speed)
  876. {
  877. creatures.push_front(it->first);
  878. }
  879. }
  880. }
  881. creatures.push_back(m_statCasualties.begin()->first);
  882. }
  883. return creatures;
  884. }
  885. list<int> CBattleLogic::PerformDefaultAction(int stackID, int &additionalInfo)
  886. {
  887. // first approach based on the statistics and weights
  888. // if this solution was fine we would develop this idea
  889. //
  890. std::map<int, int> votes;
  891. for (creature_stat::iterator it = m_statMaxDamage.begin(); it != m_statMaxDamage.end(); ++it)
  892. {
  893. votes[it->first] = 0;
  894. }
  895. votes[m_statMaxDamage.begin()->first] += m_battleHelper.GetVoteForMaxDamage();
  896. votes[m_statMinDamage.begin()->first] += m_battleHelper.GetVoteForMinDamage();
  897. if (m_statDistanceFromShooters.size())
  898. {
  899. votes[m_statDistanceFromShooters.begin()->first] += m_battleHelper.GetVoteForDistanceFromShooters();
  900. }
  901. votes[m_statDistance.begin()->first] += m_battleHelper.GetVoteForDistance();
  902. votes[m_statHitPoints.begin()->first] += m_battleHelper.GetVoteForHitPoints();
  903. votes[m_statMaxSpeed.begin()->first] += m_battleHelper.GetVoteForMaxSpeed();
  904. // get creature to attack
  905. int max_vote = 0;
  906. list<int> creatures;
  907. for (std::map<int, int>::iterator it = votes.begin(); it != votes.end(); ++it)
  908. {
  909. if (it->second > max_vote)
  910. {
  911. max_vote = it->second;
  912. creatures.push_front(it->first);
  913. }
  914. }
  915. additionalInfo = 0; // list contains creatures which shoud be attacked
  916. return creatures;
  917. }
  918. void CBattleLogic::PrintBattleAction(const BattleAction &action) // for debug purpose
  919. {
  920. std::string message("Battle action \n");
  921. message += "\taction type - ";
  922. switch (action.actionType)
  923. {
  924. case 0:
  925. message += "Cancel BattleAction\n";
  926. break;
  927. case 1:
  928. message += "Hero cast a spell\n";
  929. break;
  930. case 2:
  931. message += "Walk\n";
  932. break;
  933. case 3:
  934. message += "Defend\n";
  935. break;
  936. case 4:
  937. message += "Retreat from the battle\n";
  938. break;
  939. case 5:
  940. message += "Surrender\n";
  941. break;
  942. case 6:
  943. message += "Walk and Attack\n";
  944. break;
  945. case 7:
  946. message += "Shoot\n";
  947. break;
  948. case 8:
  949. message += "Wait\n";
  950. break;
  951. case 9:
  952. message += "Catapult\n";
  953. break;
  954. case 10:
  955. message += "Monster casts a spell\n";
  956. break;
  957. }
  958. message += "\tDestination tile: X = ";
  959. message += boost::lexical_cast<std::string>(m_battleHelper.DecodeXPosition(action.destinationTile));
  960. message += ", Y = " + boost::lexical_cast<std::string>(m_battleHelper.DecodeYPosition(action.destinationTile));
  961. message += "\nAdditional info: ";
  962. if (action.actionType == 6)// || action.actionType == 7)
  963. {
  964. message += "stack - " + boost::lexical_cast<std::string>(m_battleHelper.DecodeXPosition(action.additionalInfo));
  965. message += ", " + boost::lexical_cast<std::string>(m_battleHelper.DecodeYPosition(action.additionalInfo));
  966. message += ", creature - ";
  967. CStack *c = m_cb->battleGetStackByPos(action.additionalInfo);
  968. if (c && c->creature)
  969. {
  970. message += c->creature->nameRef;
  971. }
  972. else
  973. {
  974. message += "NULL";
  975. }
  976. }
  977. else
  978. {
  979. message += boost::lexical_cast<std::string>(action.additionalInfo);
  980. }
  981. #ifdef _WIN32
  982. HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
  983. CONSOLE_SCREEN_BUFFER_INFO csbi;
  984. GetConsoleScreenBufferInfo(hConsole, &csbi);
  985. SetConsoleTextAttribute(hConsole, FOREGROUND_GREEN | FOREGROUND_INTENSITY);
  986. #else
  987. std::string color;
  988. color = "\x1b[1;40;32m";
  989. std::cout << color;
  990. #endif
  991. std::cout << message.c_str() << std::endl;
  992. #ifdef _WIN32
  993. SetConsoleTextAttribute(hConsole, csbi.wAttributes);
  994. #else
  995. color = "\x1b[0m";
  996. std::cout << color;
  997. #endif
  998. }