CGameHandler.cpp 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334
  1. #include <boost/foreach.hpp>
  2. #include <boost/thread.hpp>
  3. #include <boost/thread/shared_mutex.hpp>
  4. #include <boost/bind.hpp>
  5. #include "CGameHandler.h"
  6. #include "CScriptCallback.h"
  7. #include "../CLua.h"
  8. #include "../CGameState.h"
  9. #include "../StartInfo.h"
  10. #include "../map.h"
  11. #include "../lib/NetPacks.h"
  12. #include "../lib/Connection.h"
  13. #include "../hch/CArtHandler.h"
  14. #include "../hch/CObjectHandler.h"
  15. #include "../hch/CTownHandler.h"
  16. #include "../hch/CBuildingHandler.h"
  17. #include "../hch/CHeroHandler.h"
  18. #include "boost/date_time/posix_time/posix_time_types.hpp" //no i/o just types
  19. #include "../lib/VCMI_Lib.h"
  20. #include "../lib/CondSh.h"
  21. #ifndef _MSC_VER
  22. #include <boost/thread/xtime.hpp>
  23. #endif
  24. extern bool end2;
  25. #include "../lib/BattleAction.h"
  26. #ifdef min
  27. #undef min
  28. #endif
  29. #ifdef max
  30. #undef max
  31. #endif
  32. #define NEW_ROUND BattleNextRound bnr;\
  33. bnr.round = gs->curB->round + 1;\
  34. sendAndApply(&bnr);
  35. boost::mutex gsm;
  36. ui32 CGameHandler::QID = 1;
  37. CondSh<bool> battleMadeAction;
  38. CondSh<BattleResult *> battleResult(NULL);
  39. std::map<ui32, CFunctionList<void(ui32)> > callbacks; //question id => callback function - for selection dialogs
  40. class CMP_stack
  41. {
  42. public:
  43. bool operator ()(const CStack* a, const CStack* b)
  44. {
  45. return (a->creature->speed)>(b->creature->speed);
  46. }
  47. } cmpst ;
  48. double distance(int3 a, int3 b)
  49. {
  50. return std::sqrt( (double)(a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y) );
  51. }
  52. //bool CGameState::checkFunc(int obid, std::string name)
  53. //{
  54. // if (objscr.find(obid)!=objscr.end())
  55. // {
  56. // if(objscr[obid].find(name)!=objscr[obid].end())
  57. // {
  58. // return true;
  59. // }
  60. // }
  61. // return false;
  62. //}
  63. PlayerStatus PlayerStatuses::operator[](ui8 player)
  64. {
  65. boost::unique_lock<boost::mutex> l(mx);
  66. if(players.find(player) != players.end())
  67. {
  68. return players[player];
  69. }
  70. else
  71. {
  72. throw std::string("No such player!");
  73. }
  74. }
  75. void PlayerStatuses::addPlayer(ui8 player)
  76. {
  77. boost::unique_lock<boost::mutex> l(mx);
  78. players[player];
  79. }
  80. bool PlayerStatuses::hasQueries(ui8 player)
  81. {
  82. boost::unique_lock<boost::mutex> l(mx);
  83. if(players.find(player) != players.end())
  84. {
  85. return players[player].queries.size();
  86. }
  87. else
  88. {
  89. throw std::string("No such player!");
  90. }
  91. }
  92. bool PlayerStatuses::checkFlag(ui8 player, bool PlayerStatus::*flag)
  93. {
  94. boost::unique_lock<boost::mutex> l(mx);
  95. if(players.find(player) != players.end())
  96. {
  97. return players[player].*flag;
  98. }
  99. else
  100. {
  101. throw std::string("No such player!");
  102. }
  103. }
  104. void PlayerStatuses::setFlag(ui8 player, bool PlayerStatus::*flag, bool val)
  105. {
  106. boost::unique_lock<boost::mutex> l(mx);
  107. if(players.find(player) != players.end())
  108. {
  109. players[player].*flag = val;
  110. }
  111. else
  112. {
  113. throw std::string("No such player!");
  114. }
  115. cv.notify_all();
  116. }
  117. void PlayerStatuses::addQuery(ui8 player, ui32 id)
  118. {
  119. boost::unique_lock<boost::mutex> l(mx);
  120. if(players.find(player) != players.end())
  121. {
  122. players[player].queries.insert(id);
  123. }
  124. else
  125. {
  126. throw std::string("No such player!");
  127. }
  128. cv.notify_all();
  129. }
  130. void PlayerStatuses::removeQuery(ui8 player, ui32 id)
  131. {
  132. boost::unique_lock<boost::mutex> l(mx);
  133. if(players.find(player) != players.end())
  134. {
  135. players[player].queries.erase(id);
  136. }
  137. else
  138. {
  139. throw std::string("No such player!");
  140. }
  141. cv.notify_all();
  142. }
  143. void CGameHandler::handleCPPObjS(std::map<int,CCPPObjectScript*> * mapa, CCPPObjectScript * script)
  144. {
  145. std::vector<int> tempv = script->yourObjects();
  146. for (unsigned i=0;i<tempv.size();i++)
  147. {
  148. (*mapa)[tempv[i]]=script;
  149. }
  150. cppscripts.insert(script);
  151. }
  152. template <typename T>
  153. void callWith(std::vector<T> args, boost::function<void(T)> fun, ui32 which)
  154. {
  155. fun(args[which]);
  156. }
  157. void CGameHandler::changeSecSkill(int ID, ui16 which, int val, bool abs)
  158. {
  159. SetSecSkill sps;
  160. sps.id = ID;
  161. sps.which = which;
  162. sps.abs = abs;
  163. sps.val = val;
  164. sendAndApply(&sps);
  165. }
  166. void CGameHandler::changePrimSkill(int ID, int which, int val, bool abs)
  167. {
  168. SetPrimSkill sps;
  169. sps.id = ID;
  170. sps.which = which;
  171. sps.abs = abs;
  172. sps.val = val;
  173. sendAndApply(&sps);
  174. if(which==4) //only for exp - hero may level up
  175. {
  176. CGHeroInstance *hero = static_cast<CGHeroInstance *>(gs->map->objects[ID]);
  177. if(hero->exp >= VLC->heroh->reqExp(hero->level+1)) //new level
  178. {
  179. //give prim skill
  180. std::cout << hero->name <<" got level "<<hero->level<<std::endl;
  181. int r = rand()%100, pom=0, x=0;
  182. int std::pair<int,int>::*g = (hero->level>9) ? (&std::pair<int,int>::second) : (&std::pair<int,int>::first);
  183. for(;x<PRIMARY_SKILLS;x++)
  184. {
  185. pom += hero->type->heroClass->primChance[x].*g;
  186. if(r<pom)
  187. break;
  188. }
  189. std::cout << "Bohater dostaje umiejetnosc pierwszorzedna " << x << " (wynik losowania "<<r<<")"<<std::endl;
  190. SetPrimSkill sps;
  191. sps.id = ID;
  192. sps.which = x;
  193. sps.abs = false;
  194. sps.val = 1;
  195. sendAndApply(&sps);
  196. HeroLevelUp hlu;
  197. hlu.heroid = ID;
  198. hlu.primskill = x;
  199. hlu.level = hero->level+1;
  200. //picking sec. skills for choice
  201. std::set<int> basicAndAdv, expert, none;
  202. for(int i=0;i<SKILL_QUANTITY;i++) none.insert(i);
  203. for(unsigned i=0;i<hero->secSkills.size();i++)
  204. {
  205. if(hero->secSkills[i].second < 2)
  206. basicAndAdv.insert(hero->secSkills[i].first);
  207. else
  208. expert.insert(hero->secSkills[i].first);
  209. none.erase(hero->secSkills[i].first);
  210. }
  211. if(hero->secSkills.size() < hero->type->heroClass->skillLimit) //free skill slot
  212. {
  213. hlu.skills.push_back(hero->type->heroClass->chooseSecSkill(none)); //new skill
  214. }
  215. else
  216. {
  217. int s = hero->type->heroClass->chooseSecSkill(basicAndAdv);
  218. hlu.skills.push_back(s);
  219. basicAndAdv.erase(s);
  220. }
  221. if(basicAndAdv.size())
  222. {
  223. hlu.skills.push_back(hero->type->heroClass->chooseSecSkill(basicAndAdv)); //new skill
  224. }
  225. else if(hero->secSkills.size() < hero->type->heroClass->skillLimit)
  226. {
  227. hlu.skills.push_back(hero->type->heroClass->chooseSecSkill(none)); //new skill
  228. }
  229. boost::function<void(ui32)> callback = boost::function<void(ui32)>(boost::bind(callWith<ui16>,hlu.skills,boost::function<void(ui16)>(boost::bind(&CGameHandler::changeSecSkill,this,ID,_1,1,0)),_1));
  230. applyAndAsk(&hlu,hero->tempOwner,callback); //call changeSecSkill with appropriate args when client responds
  231. }
  232. }
  233. }
  234. void CGameHandler::startBattle(CCreatureSet army1, CCreatureSet army2, int3 tile, CGHeroInstance *hero1, CGHeroInstance *hero2)
  235. {
  236. BattleInfo *curB = new BattleInfo;
  237. setupBattle(curB, tile, army1, army2, hero1, hero2); //battle start
  238. NEW_ROUND;
  239. //tactic round
  240. {
  241. NEW_ROUND;
  242. if( (hero1 && hero1->getSecSkillLevel(19)>=0) ||
  243. ( hero2 && hero2->getSecSkillLevel(19)>=0) )//someone has tactics
  244. {
  245. //TODO: tactic round (round -1)
  246. }
  247. }
  248. //main loop
  249. while(!battleResult.get()) //till the end of the battle ;]
  250. {
  251. NEW_ROUND;
  252. std::vector<CStack*> & stacks = (gs->curB->stacks);
  253. const BattleInfo & curB = *gs->curB;
  254. //stack loop
  255. for(unsigned i=0;i<stacks.size() && !battleResult.get();i++)
  256. {
  257. if(!stacks[i]->alive) continue;//indicates imposiibility of making action for this dead unit
  258. BattleSetActiveStack sas;
  259. sas.stack = stacks[i]->ID;
  260. sendAndApply(&sas);
  261. boost::unique_lock<boost::mutex> lock(battleMadeAction.mx);
  262. while(!battleMadeAction.data)
  263. battleMadeAction.cond.wait(lock);
  264. battleMadeAction.data = false;
  265. checkForBattleEnd(stacks);
  266. }
  267. }
  268. //unblock engaged players
  269. if(hero1->tempOwner<PLAYER_LIMIT)
  270. states.setFlag(hero1->tempOwner,&PlayerStatus::engagedIntoBattle,false);
  271. if(hero2 && hero2->tempOwner<PLAYER_LIMIT)
  272. states.setFlag(hero2->tempOwner,&PlayerStatus::engagedIntoBattle,false);
  273. //end battle, remove all info, free memory
  274. sendAndApply(battleResult.data);
  275. delete battleResult.data;
  276. //for(int i=0;i<stacks.size();i++)
  277. // delete stacks[i];
  278. //delete curB;
  279. //curB = NULL;
  280. }
  281. void prepareAttack(BattleAttack &bat, CStack *att, CStack *def)
  282. {
  283. bat.stackAttacking = att->ID;
  284. bat.bsa.stackAttacked = def->ID;
  285. bat.bsa.damageAmount = BattleInfo::calculateDmg(att, def);//counting dealt damage
  286. //applying damages
  287. bat.bsa.killedAmount = bat.bsa.damageAmount / def->creature->hitPoints;
  288. unsigned damageFirst = bat.bsa.damageAmount % def->creature->hitPoints;
  289. if( def->firstHPleft <= damageFirst )
  290. {
  291. bat.bsa.killedAmount++;
  292. bat.bsa.newHP = def->firstHPleft + def->creature->hitPoints - damageFirst;
  293. }
  294. else
  295. {
  296. bat.bsa.newHP = def->firstHPleft - damageFirst;
  297. }
  298. if(def->amount <= bat.bsa.killedAmount) //stack killed
  299. {
  300. bat.bsa.newAmount = 0;
  301. bat.bsa.flags |= 1;
  302. bat.bsa.killedAmount = def->amount; //we cannot kill more creatures than we have
  303. }
  304. else
  305. {
  306. bat.bsa.newAmount = def->amount - bat.bsa.killedAmount;
  307. }
  308. }
  309. void CGameHandler::handleConnection(std::set<int> players, CConnection &c)
  310. {
  311. try
  312. {
  313. ui16 pom;
  314. while(!end2)
  315. {
  316. c >> pom;
  317. bool blockvis = false;
  318. switch(pom)
  319. {
  320. case 100: //my interface ended its turn
  321. {
  322. states.setFlag(gs->currentPlayer,&PlayerStatus::makingTurn,false);
  323. break;
  324. }
  325. case 500:
  326. {
  327. si32 id;
  328. c >> id;
  329. RemoveObject rh(id);
  330. sendAndApply(&rh);
  331. break;
  332. }
  333. case 501://interface wants to move hero
  334. {
  335. int3 start, end;
  336. si32 id;
  337. c >> id >> start >> end;
  338. int3 hmpos = end + int3(-1,0,0);
  339. TerrainTile t = gs->map->terrain[hmpos.x][hmpos.y][hmpos.z];
  340. CGHeroInstance *h = static_cast<CGHeroInstance *>(gs->map->objects[id]);
  341. int cost = (int)((double)h->getTileCost(t.tertype,t.malle,t.nuine) * distance(start,end));
  342. TryMoveHero tmh;
  343. tmh.id = id;
  344. tmh.start = start;
  345. tmh.end = end;
  346. tmh.result = 0;
  347. tmh.movePoints = h->movement;
  348. if((h->getOwner() != gs->currentPlayer) || //not turn of that hero
  349. (distance(start,end)>=1.5) || //tiles are not neighouring
  350. (h->movement < cost) || //lack of movement points
  351. (t.tertype == rock) || //rock
  352. (!h->canWalkOnSea() && t.tertype == water) ||
  353. (t.blocked && !t.visitable) ) //tile is blocked andnot visitable
  354. goto fail;
  355. //check if there is blocking visitable object
  356. blockvis = false;
  357. tmh.movePoints = h->movement = (h->movement-cost); //take move points
  358. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  359. {
  360. if(obj->blockVisit)
  361. {
  362. blockvis = true;
  363. break;
  364. }
  365. }
  366. //we start moving
  367. if(blockvis)//interaction with blocking object (like resources)
  368. {
  369. sendAndApply(&tmh); //failed to move to that tile but we visit object
  370. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  371. {
  372. if (obj->blockVisit)
  373. {
  374. //if(gs->checkFunc(obj->ID,"heroVisit")) //script function
  375. // gs->objscr[obj->ID]["heroVisit"]->onHeroVisit(obj,h->subID);
  376. if(obj->state) //hard-coded function
  377. obj->state->onHeroVisit(obj->id,h->id);
  378. }
  379. }
  380. break;
  381. }
  382. else //normal move
  383. {
  384. tmh.result = 1;
  385. BOOST_FOREACH(CGObjectInstance *obj, gs->map->terrain[start.x-1][start.y][start.z].visitableObjects)
  386. {
  387. //TODO: allow to handle this in script-languages
  388. if(obj->state) //hard-coded function
  389. obj->state->onHeroLeave(obj->id,h->id);
  390. }
  391. //reveal fog of war
  392. int heroSight = h->getSightDistance();
  393. int xbeg = start.x - heroSight - 2;
  394. if(xbeg < 0)
  395. xbeg = 0;
  396. int xend = start.x + heroSight + 2;
  397. if(xend >= gs->map->width)
  398. xend = gs->map->width;
  399. int ybeg = start.y - heroSight - 2;
  400. if(ybeg < 0)
  401. ybeg = 0;
  402. int yend = start.y + heroSight + 2;
  403. if(yend >= gs->map->height)
  404. yend = gs->map->height;
  405. for(int xd=xbeg; xd<xend; ++xd) //revealing part of map around heroes
  406. {
  407. for(int yd=ybeg; yd<yend; ++yd)
  408. {
  409. int deltaX = (hmpos.x-xd)*(hmpos.x-xd);
  410. int deltaY = (hmpos.y-yd)*(hmpos.y-yd);
  411. if(deltaX+deltaY<h->getSightDistance()*h->getSightDistance())
  412. {
  413. if(gs->players[h->getOwner()].fogOfWarMap[xd][yd][hmpos.z] == 0)
  414. {
  415. tmh.fowRevealed.insert(int3(xd,yd,hmpos.z));
  416. }
  417. }
  418. }
  419. }
  420. sendAndApply(&tmh);
  421. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)//call objects if they are visited
  422. {
  423. //if(gs->checkFunc(obj->ID,"heroVisit")) //script function
  424. // gs->objscr[obj->ID]["heroVisit"]->onHeroVisit(obj,h->subID);
  425. if(obj->state) //hard-coded function
  426. obj->state->onHeroVisit(obj->id,h->id);
  427. }
  428. }
  429. break;
  430. fail:
  431. sendAndApply(&tmh);
  432. break;
  433. }
  434. case 502: //swap creatures in garrison
  435. {
  436. ui8 what, p1, p2; si32 id1, id2;
  437. c >> what >> id1 >> p1 >> id2 >> p2;
  438. CArmedInstance *s1 = static_cast<CArmedInstance*>(gs->map->objects[id1]),
  439. *s2 = static_cast<CArmedInstance*>(gs->map->objects[id2]);
  440. CCreatureSet *S1 = &s1->army, *S2 = &s2->army;
  441. if(what==1) //swap
  442. {
  443. int pom = S2->slots[p2].first;
  444. S2->slots[p2].first = S1->slots[p1].first;
  445. S1->slots[p1].first = pom;
  446. int pom2 = S2->slots[p2].second;
  447. S2->slots[p2].second = S1->slots[p1].second;
  448. S1->slots[p1].second = pom2;
  449. if(!S1->slots[p1].second)
  450. S1->slots.erase(p1);
  451. if(!S2->slots[p2].second)
  452. S2->slots.erase(p2);
  453. }
  454. else if(what==2)//merge
  455. {
  456. if(S1->slots[p1].first != S2->slots[p2].first) break; //not same creature
  457. S2->slots[p2].second += S1->slots[p1].second;
  458. S1->slots[p1].first = NULL;
  459. S1->slots[p1].second = 0;
  460. S1->slots.erase(p1);
  461. }
  462. else if(what==3) //split
  463. {
  464. si32 val;
  465. c >> val;
  466. if(S2->slots.find(p2) != S2->slots.end()) break; //slot not free
  467. S2->slots[p2].first = S1->slots[p1].first;
  468. S2->slots[p2].second = val;
  469. S1->slots[p1].second -= val;
  470. if(!S1->slots[p1].second) //if we've moved all creatures
  471. S1->slots.erase(p1);
  472. }
  473. if((s1->ID==34 && !S1->slots.size()) //it's not allowed to take last stack from hero army!
  474. || (s2->ID==34 && !S2->slots.size()))
  475. {
  476. break;
  477. }
  478. SetGarrisons sg;
  479. sg.garrs[id1] = *S1;
  480. if(s1 != s2)
  481. sg.garrs[id2] = *S2;
  482. sendAndApply(&sg);
  483. break;
  484. }
  485. case 503:
  486. {
  487. si32 id;
  488. ui8 pos;
  489. c >> id >> pos;
  490. CArmedInstance *s1 = static_cast<CArmedInstance*>(gs->map->objects[id]);
  491. s1->army.slots.erase(pos);
  492. SetGarrisons sg;
  493. sg.garrs[id] = s1->army;
  494. sendAndApply(&sg);
  495. break;
  496. }
  497. case 504:
  498. {
  499. si32 tid, bid;
  500. c >> tid >> bid;
  501. CGTownInstance * t = static_cast<CGTownInstance*>(gs->map->objects[tid]);
  502. CBuilding * b = VLC->buildh->buildings[t->subID][bid];
  503. for(int i=0;i<RESOURCE_QUANTITY;i++)
  504. if(b->resources[i] > gs->players[t->tempOwner].resources[i])
  505. break; //no res
  506. //TODO: check requirements
  507. //TODO: check if building isn't forbidden
  508. NewStructures ns;
  509. ns.tid = tid;
  510. if(bid>36) //upg dwelling
  511. {
  512. if(t->getHordeLevel(0) == (bid-37))
  513. ns.bid.insert(19);
  514. else if(t->getHordeLevel(1) == (bid-37))
  515. ns.bid.insert(25);
  516. }
  517. else if(bid >= 30) //bas. dwelling
  518. {
  519. SetAvailableCreatures ssi;
  520. ssi.tid = tid;
  521. ssi.creatures = t->strInfo.creatures;
  522. ssi.creatures[bid-30] = VLC->creh->creatures[t->town->basicCreatures[bid-30]].growth;
  523. sendAndApply(&ssi);
  524. }
  525. ns.bid.insert(bid);
  526. ns.builded = t->builded + 1;
  527. sendAndApply(&ns);
  528. SetResources sr;
  529. sr.player = t->tempOwner;
  530. sr.res = gs->players[t->tempOwner].resources;
  531. for(int i=0;i<7;i++)
  532. sr.res[i]-=b->resources[i];
  533. sendAndApply(&sr);
  534. break;
  535. }
  536. case 506: //recruit creature
  537. {
  538. si32 objid, ser=-1; //ser - used dwelling level
  539. ui32 crid, cram; //recruited creature id and amount
  540. c >> objid >> crid >> cram;
  541. CGTownInstance * t = static_cast<CGTownInstance*>(gs->map->objects[objid]);
  542. //verify
  543. bool found = false;
  544. typedef std::pair<const int,int> Parka;
  545. for(std::map<si32,ui32>::iterator av = t->strInfo.creatures.begin(); av!=t->strInfo.creatures.end(); av++)
  546. {
  547. if( ( found = (crid == t->town->basicCreatures[av->first]) ) //creature is available among basic cretures
  548. || (found = (crid == t->town->upgradedCreatures[av->first])) )//creature is available among upgraded cretures
  549. {
  550. cram = std::min(cram,av->second); //reduce recruited amount up to available amount
  551. ser = av->first;
  552. break;
  553. }
  554. }
  555. int slot = t->army.getSlotFor(crid);
  556. if(!found || //no such creature
  557. cram > VLC->creh->creatures[crid].maxAmount(gs->players[t->tempOwner].resources) || //lack of resources
  558. cram<=0 ||
  559. slot<0 )
  560. break;
  561. //recruit
  562. SetResources sr;
  563. sr.player = t->tempOwner;
  564. for(int i=0;i<RESOURCE_QUANTITY;i++)
  565. sr.res[i] = gs->players[t->tempOwner].resources[i] - (VLC->creh->creatures[crid].cost[i] * cram);
  566. SetAvailableCreatures sac;
  567. sac.tid = objid;
  568. sac.creatures = t->strInfo.creatures;
  569. sac.creatures[ser] -= cram;
  570. SetGarrisons sg;
  571. sg.garrs[objid] = t->army;
  572. if(sg.garrs[objid].slots.find(slot) == sg.garrs[objid].slots.end()) //take a free slot
  573. {
  574. sg.garrs[objid].slots[slot] = std::make_pair(crid,cram);
  575. }
  576. else //add creatures to a already existing stack
  577. {
  578. sg.garrs[objid].slots[slot].second += cram;
  579. }
  580. sendAndApply(&sr);
  581. sendAndApply(&sac);
  582. sendAndApply(&sg);
  583. break;
  584. }
  585. case 507://upgrade creature
  586. {
  587. ui32 objid, upgID;
  588. ui8 pos;
  589. c >> objid >> pos >> upgID;
  590. CArmedInstance *obj = static_cast<CArmedInstance*>(gs->map->objects[objid]);
  591. UpgradeInfo ui = gs->getUpgradeInfo(obj,pos);
  592. int player = obj->tempOwner;
  593. int crQuantity = obj->army.slots[pos].second;
  594. //check if upgrade is possible
  595. if(ui.oldID<0 || !vstd::contains(ui.newID,upgID))
  596. break;
  597. //check if player has enough resources
  598. for(int i=0;i<ui.cost.size();i++)
  599. {
  600. for (std::set<std::pair<int,int> >::iterator j=ui.cost[i].begin(); j!=ui.cost[i].end(); j++)
  601. {
  602. if(gs->players[player].resources[j->first] < j->second*crQuantity)
  603. goto upgend;
  604. }
  605. }
  606. //take resources
  607. for(int i=0;i<ui.cost.size();i++)
  608. {
  609. for (std::set<std::pair<int,int> >::iterator j=ui.cost[i].begin(); j!=ui.cost[i].end(); j++)
  610. {
  611. SetResource sr;
  612. sr.player = player;
  613. sr.resid = j->first;
  614. sr.val = gs->players[player].resources[j->first] - j->second*crQuantity;
  615. sendAndApply(&sr);
  616. }
  617. }
  618. {
  619. //upgrade creature
  620. SetGarrisons sg;
  621. sg.garrs[objid] = obj->army;
  622. sg.garrs[objid].slots[pos].first = upgID;
  623. sendAndApply(&sg);
  624. }
  625. upgend:
  626. break;
  627. }
  628. case 508: //garrison swap
  629. {
  630. si32 tid;
  631. c >> tid;
  632. CGTownInstance *town = gs->getTown(tid);
  633. if(!town->garrisonHero && town->visitingHero) //visiting => garrison, merge armies
  634. {
  635. CCreatureSet csn = town->visitingHero->army, cso = town->army;
  636. while(!cso.slots.empty())//while there are unmoved creatures
  637. {
  638. int pos = csn.getSlotFor(cso.slots.begin()->second.first);
  639. if(pos<0)
  640. goto handleConEnd;
  641. if(csn.slots.find(pos)!=csn.slots.end()) //add creatures to the existing stack
  642. {
  643. csn.slots[pos].second += cso.slots.begin()->second.second;
  644. }
  645. else //move stack on the free pos
  646. {
  647. csn.slots[pos].first = cso.slots.begin()->second.first;
  648. csn.slots[pos].second = cso.slots.begin()->second.second;
  649. }
  650. cso.slots.erase(cso.slots.begin());
  651. }
  652. SetGarrisons sg;
  653. sg.garrs[town->visitingHero->id] = csn;
  654. sg.garrs[town->id] = csn;
  655. sendAndApply(&sg);
  656. SetHeroesInTown intown;
  657. intown.tid = tid;
  658. intown.visiting = -1;
  659. intown.garrison = town->visitingHero->id;
  660. sendAndApply(&intown);
  661. }
  662. else if (town->garrisonHero && !town->visitingHero) //move hero out of the garrison
  663. {
  664. SetHeroesInTown intown;
  665. intown.tid = tid;
  666. intown.garrison = -1;
  667. intown.visiting = town->garrisonHero->id;
  668. sendAndApply(&intown);
  669. //town will be empty
  670. SetGarrisons sg;
  671. sg.garrs[tid] = CCreatureSet();
  672. sendAndApply(&sg);
  673. }
  674. else if (town->garrisonHero && town->visitingHero) //swap visiting and garrison hero
  675. {
  676. SetGarrisons sg;
  677. sg.garrs[town->id] = town->visitingHero->army;
  678. sg.garrs[town->garrisonHero->id] = town->garrisonHero->army;
  679. //sg.garrs[town->visitingHero->id] = town->visitingHero->army;
  680. SetHeroesInTown intown;
  681. intown.tid = tid;
  682. intown.garrison = town->visitingHero->id;
  683. intown.visiting = town->garrisonHero->id;
  684. sendAndApply(&intown);
  685. sendAndApply(&sg);
  686. }
  687. else
  688. {
  689. std::cout << "Warning, wrong garrison swap command for " << tid << std::endl;
  690. }
  691. break;
  692. }
  693. case 509: //swap artifacts
  694. {
  695. si32 hid1, hid2;
  696. ui16 slot1, slot2;
  697. c >> hid1 >> slot1 >> hid2 >> slot2;
  698. CGHeroInstance *h1 = gs->getHero(hid1), *h2 = gs->getHero(hid2);
  699. if((distance(h1->pos,h2->pos) > 1.0) || (h1->tempOwner != h2->tempOwner))
  700. break;
  701. int a1=h1->getArtAtPos(slot1), a2=h2->getArtAtPos(slot2);
  702. h2->setArtAtPos(slot2,a1);
  703. h1->setArtAtPos(slot1,a2);
  704. SetHeroArtifacts sha;
  705. sha.hid = hid1;
  706. sha.artifacts = h1->artifacts;
  707. sha.artifWorn = h1->artifWorn;
  708. sendAndApply(&sha);
  709. if(hid1 != hid2)
  710. {
  711. sha.hid = hid2;
  712. sha.artifacts = h2->artifacts;
  713. sha.artifWorn = h2->artifWorn;
  714. sendAndApply(&sha);
  715. }
  716. break;
  717. }
  718. case 510: //buy artifact
  719. {
  720. ui32 hid;
  721. si32 aid, bid;
  722. c >> hid >> aid;
  723. CGHeroInstance *hero = gs->getHero(hid);
  724. CGTownInstance *town = hero->visitedTown;
  725. if(aid==0)
  726. {
  727. if(!vstd::contains(town->builtBuildings,si32(0)))
  728. break;
  729. SetResource sr;
  730. sr.player = hero->tempOwner;
  731. sr.resid = 6;
  732. sr.val = gs->players[hero->tempOwner].resources[6] - 500;
  733. sendAndApply(&sr);
  734. SetHeroArtifacts sha;
  735. sha.hid = hid;
  736. sha.artifacts = hero->artifacts;
  737. sha.artifWorn = hero->artifWorn;
  738. sha.artifWorn[17] = 0;
  739. sendAndApply(&sha);
  740. }
  741. else if(aid < 7 && aid > 3) //war machine
  742. {
  743. int price = VLC->arth->artifacts[aid].price;
  744. if(vstd::contains(hero->artifWorn,ui16(9+aid)) //hero already has this machine
  745. || !vstd::contains(town->builtBuildings,si32(16)) //no blackismith
  746. || gs->players[hero->tempOwner].resources[6] < price //no gold
  747. || town->town->warMachine!= aid ) //this machine is not available here (//TODO: support ballista yard in stronghold)
  748. {
  749. break;
  750. }
  751. SetResource sr;
  752. sr.player = hero->tempOwner;
  753. sr.resid = 6;
  754. sr.val = gs->players[hero->tempOwner].resources[6] - price;
  755. sendAndApply(&sr);
  756. SetHeroArtifacts sha;
  757. sha.hid = hid;
  758. sha.artifacts = hero->artifacts;
  759. sha.artifWorn = hero->artifWorn;
  760. sha.artifWorn[9+aid] = aid;
  761. sendAndApply(&sha);
  762. }
  763. break;
  764. }
  765. case 511: //trade at marketplace
  766. {
  767. ui8 player;
  768. ui32 mode, id1, id2, val;
  769. c >> player >> mode >> id1 >> id2 >> val;
  770. val = std::min(si32(val),gs->players[player].resources[id1]);
  771. double uzysk = (double)gs->resVals[id1] * val * gs->getMarketEfficiency(player);
  772. uzysk /= gs->resVals[id2];
  773. SetResource sr;
  774. sr.player = player;
  775. sr.resid = id1;
  776. sr.val = gs->players[player].resources[id1] - val;
  777. sendAndApply(&sr);
  778. sr.resid = id2;
  779. sr.val = gs->players[player].resources[id2] + (int)uzysk;
  780. sendAndApply(&sr);
  781. break;
  782. }
  783. case 2001:
  784. {
  785. ui32 qid, answer;
  786. c >> qid >> answer;
  787. gsm.lock();
  788. CFunctionList<void(ui32)> callb = callbacks[qid];
  789. callbacks.erase(qid);
  790. gsm.unlock();
  791. callb(answer);
  792. break;
  793. }
  794. case 3002:
  795. {
  796. BattleAction ba;
  797. c >> ba;
  798. switch(ba.actionType)
  799. {
  800. case 2: //walk
  801. {
  802. moveStack(ba.stackNumber,ba.destinationTile);
  803. break;
  804. }
  805. case 3: //defend
  806. {
  807. break;
  808. }
  809. case 4: //retreat/flee
  810. {
  811. //TODO: check if fleeing is possible (e.g. enemy may have Shackles of War)
  812. //TODO: calculate casualties
  813. //TODO: remove retreating hero from map and place it in recrutation list
  814. BattleResult *br = new BattleResult;
  815. br->result = 1;
  816. br->winner = !ba.side; //fleeing side loses
  817. gs->curB->calculateCasualties(br->casualties);
  818. battleResult.set(br);
  819. break;
  820. }
  821. case 6: //walk or attack
  822. {
  823. moveStack(ba.stackNumber,ba.destinationTile);
  824. CStack *curStack = gs->curB->getStack(ba.stackNumber),
  825. *stackAtEnd = gs->curB->getStackT(ba.additionalInfo);
  826. if((curStack->position != ba.destinationTile) || //we wasn't able to reach destination tile
  827. (BattleInfo::mutualPosition(ba.destinationTile,ba.additionalInfo)<0) ) //destination tile is not neighbouring with enemy stack
  828. return;
  829. BattleAttack bat;
  830. prepareAttack(bat,curStack,stackAtEnd);
  831. sendAndApply(&bat);
  832. break;
  833. }
  834. case 7: //shoot
  835. {
  836. CStack *curStack = gs->curB->getStack(ba.stackNumber),
  837. *destStack= gs->curB->getStackT(ba.destinationTile);
  838. BattleAttack bat;
  839. prepareAttack(bat,curStack,destStack);
  840. bat.flags |= 1;
  841. sendAndApply(&bat);
  842. break;
  843. }
  844. }
  845. battleMadeAction.setn(true);
  846. //sprawdzic czy po tej akcji ktoras strona nie wygrala bitwy
  847. break;
  848. }
  849. default:
  850. #ifndef __GNUC__
  851. throw std::exception("Not supported client message!");
  852. #else
  853. throw std::exception();
  854. #endif
  855. break;
  856. }
  857. }
  858. }
  859. catch (const std::exception& e)
  860. {
  861. std::cerr << e.what() << std::endl;
  862. end2 = true;
  863. }
  864. catch (const std::exception * e)
  865. {
  866. std::cerr << e->what()<< std::endl;
  867. end2 = true;
  868. delete e;
  869. }
  870. catch(...)
  871. {
  872. end2 = true;
  873. }
  874. handleConEnd:
  875. ;
  876. }
  877. void CGameHandler::moveStack(int stack, int dest)
  878. {
  879. CStack *curStack = gs->curB->getStack(stack),
  880. *stackAtEnd = gs->curB->getStackT(dest);
  881. //initing necessary tables
  882. bool accessibility[187];
  883. if(curStack->creature->isDoubleWide())
  884. gs->curB->getAccessibilityMapForTwoHex(accessibility,curStack->attackerOwned,curStack->ID);
  885. else
  886. gs->curB->getAccessibilityMap(accessibility,curStack->ID);
  887. if((stackAtEnd && stackAtEnd!=curStack && stackAtEnd->alive) || !accessibility[dest])
  888. return;
  889. //if(dists[dest] > curStack->creature->speed && !(stackAtEnd && dists[dest] == curStack->creature->speed+1)) //we can attack a stack if we can go to adjacent hex
  890. // return false;
  891. std::vector<int> path = gs->curB->getPath(curStack->position,dest,accessibility);
  892. int tilesToMove = std::max((int)path.size()-curStack->creature->speed, 0);
  893. for(int v=path.size()-1; v>=tilesToMove; --v)
  894. {
  895. //inform clients about move
  896. BattleStackMoved sm;
  897. sm.stack = curStack->ID;
  898. sm.tile = path[v];
  899. if(v==path.size()-1) //move start - set flag
  900. sm.flags |= 1;
  901. if(v==0) //move end - set flag
  902. sm.flags |= 2;
  903. sendAndApply(&sm);
  904. }
  905. }
  906. CGameHandler::CGameHandler(void)
  907. {
  908. gs = NULL;
  909. }
  910. CGameHandler::~CGameHandler(void)
  911. {
  912. delete gs;
  913. }
  914. void CGameHandler::init(StartInfo *si, int Seed)
  915. {
  916. Mapa *map = new Mapa(si->mapname);
  917. std::cout << "Map loaded!" << std::endl;
  918. gs = new CGameState();
  919. std::cout << "Gamestate created!" << std::endl;
  920. gs->init(si,map,Seed);
  921. std::cout << "Gamestate initialized!" << std::endl;
  922. /****************************LUA OBJECT SCRIPTS************************************************/
  923. //std::vector<std::string> * lf = CLuaHandler::searchForScripts("scripts/lua/objects"); //files
  924. //for (int i=0; i<lf->size(); i++)
  925. //{
  926. // try
  927. // {
  928. // std::vector<std::string> * temp = CLuaHandler::functionList((*lf)[i]);
  929. // CLuaObjectScript * objs = new CLuaObjectScript((*lf)[i]);
  930. // CLuaCallback::registerFuncs(objs->is);
  931. // //objs
  932. // for (int j=0; j<temp->size(); j++)
  933. // {
  934. // int obid ; //obj ID
  935. // int dspos = (*temp)[j].find_first_of('_');
  936. // obid = atoi((*temp)[j].substr(dspos+1,(*temp)[j].size()-dspos-1).c_str());
  937. // std::string fname = (*temp)[j].substr(0,dspos);
  938. // if (skrypty->find(obid)==skrypty->end())
  939. // skrypty->insert(std::pair<int, std::map<std::string, CObjectScript*> >(obid,std::map<std::string,CObjectScript*>()));
  940. // (*skrypty)[obid].insert(std::pair<std::string, CObjectScript*>(fname,objs));
  941. // }
  942. // delete temp;
  943. // }HANDLE_EXCEPTION
  944. //}
  945. //delete lf;
  946. }
  947. int lowestSpeed(CGHeroInstance * chi)
  948. {
  949. std::map<si32,std::pair<ui32,si32> >::iterator i = chi->army.slots.begin();
  950. int ret = VLC->creh->creatures[(*i++).second.first].speed;
  951. for (;i!=chi->army.slots.end();i++)
  952. {
  953. ret = std::min(ret,VLC->creh->creatures[(*i).second.first].speed);
  954. }
  955. return ret;
  956. }
  957. int valMovePoints(CGHeroInstance * chi)
  958. {
  959. int ret = 1270+70*lowestSpeed(chi);
  960. if (ret>2000)
  961. ret=2000;
  962. //TODO: additional bonuses (but they aren't currently stored in chi)
  963. return ret;
  964. }
  965. void CGameHandler::newTurn()
  966. {
  967. NewTurn n;
  968. n.day = gs->day + 1;
  969. n.resetBuilded = true;
  970. for ( std::map<ui8, PlayerState>::iterator i=gs->players.begin() ; i!=gs->players.end();i++)
  971. {
  972. if(i->first>=PLAYER_LIMIT) continue;
  973. SetResources r;
  974. r.player = i->first;
  975. for(int j=0;j<RESOURCE_QUANTITY;j++)
  976. r.res[j] = i->second.resources[j];
  977. for (unsigned j=0;j<(*i).second.heroes.size();j++) //handle heroes
  978. {
  979. NewTurn::Hero h;
  980. h.id = (*i).second.heroes[j]->id;
  981. h.move = valMovePoints((*i).second.heroes[j]);
  982. h.mana = (*i).second.heroes[j]->mana;
  983. n.heroes.insert(h);
  984. }
  985. for(std::vector<CGTownInstance *>::iterator j=i->second.towns.begin();j!=i->second.towns.end();j++)//handle towns
  986. {
  987. if(gs->getDate(1)==7) //first day of week
  988. {
  989. SetAvailableCreatures sac;
  990. sac.tid = (**j).id;
  991. sac.creatures = (**j).strInfo.creatures;
  992. for(int k=0;k<CREATURES_PER_TOWN;k++) //creature growths
  993. {
  994. if((**j).creatureDwelling(k))//there is dwelling (k-level)
  995. sac.creatures[k] += (**j).creatureGrowth(k);
  996. }
  997. n.cres.push_back(sac);
  998. }
  999. if((gs->day) && i->first<PLAYER_LIMIT)//not the first day and town not neutral
  1000. r.res[6] += (**j).dailyIncome();
  1001. }
  1002. n.res.push_back(r);
  1003. }
  1004. sendAndApply(&n);
  1005. for (std::set<CCPPObjectScript *>::iterator i=cppscripts.begin();i!=cppscripts.end();i++)
  1006. {
  1007. (*i)->newTurn();
  1008. }
  1009. }
  1010. void CGameHandler::run()
  1011. {
  1012. BOOST_FOREACH(CConnection *cc, conns)
  1013. {//init conn.
  1014. ui8 quantity, pom;
  1015. //ui32 seed;
  1016. (*cc) << gs->scenarioOps->mapname << gs->map->checksum << gs->seed;
  1017. (*cc) >> quantity;
  1018. for(int i=0;i<quantity;i++)
  1019. {
  1020. (*cc) >> pom;
  1021. gsm.lock();
  1022. connections[pom] = cc;
  1023. gsm.unlock();
  1024. }
  1025. }
  1026. for(std::set<CConnection*>::iterator i = conns.begin(); i!=conns.end();i++)
  1027. {
  1028. std::set<int> pom;
  1029. for(std::map<int,CConnection*>::iterator j = connections.begin(); j!=connections.end();j++)
  1030. if(j->second == *i)
  1031. pom.insert(j->first);
  1032. boost::thread(boost::bind(&CGameHandler::handleConnection,this,pom,boost::ref(**i)));
  1033. }
  1034. /****************************SCRIPTS************************************************/
  1035. //std::map<int, std::map<std::string, CObjectScript*> > * skrypty = &objscr; //alias for easier access
  1036. /****************************C++ OBJECT SCRIPTS************************************************/
  1037. std::map<int,CCPPObjectScript*> scripts;
  1038. CScriptCallback * csc = new CScriptCallback();
  1039. csc->gh = this;
  1040. handleCPPObjS(&scripts,new CVisitableOPH(csc));
  1041. handleCPPObjS(&scripts,new CVisitableOPW(csc));
  1042. handleCPPObjS(&scripts,new CPickable(csc));
  1043. handleCPPObjS(&scripts,new CMines(csc));
  1044. handleCPPObjS(&scripts,new CTownScript(csc));
  1045. handleCPPObjS(&scripts,new CHeroScript(csc));
  1046. handleCPPObjS(&scripts,new CMonsterS(csc));
  1047. handleCPPObjS(&scripts,new CCreatureGen(csc));
  1048. /****************************INITIALIZING OBJECT SCRIPTS************************************************/
  1049. //std::string temps("newObject");
  1050. for (unsigned i=0; i<gs->map->objects.size(); i++)
  1051. {
  1052. //c++ scripts
  1053. if (scripts.find(gs->map->objects[i]->ID) != scripts.end())
  1054. {
  1055. gs->map->objects[i]->state = scripts[gs->map->objects[i]->ID];
  1056. gs->map->objects[i]->state->newObject(gs->map->objects[i]->id);
  1057. }
  1058. else
  1059. {
  1060. gs->map->objects[i]->state = NULL;
  1061. }
  1062. //// lua scripts
  1063. //if(checkFunc(map->objects[i]->ID,temps))
  1064. // (*skrypty)[map->objects[i]->ID][temps]->newObject(map->objects[i]);
  1065. }
  1066. for(std::map<ui8,PlayerState>::iterator i = gs->players.begin(); i != gs->players.end(); i++)
  1067. states.addPlayer(i->first);
  1068. while (!end2)
  1069. {
  1070. newTurn();
  1071. for(std::map<ui8,PlayerState>::iterator i = gs->players.begin(); i != gs->players.end(); i++)
  1072. {
  1073. if((i->second.towns.size()==0 && i->second.heroes.size()==0) || i->second.color<0 || i->first>=PLAYER_LIMIT ) continue; //players has not towns/castle - loser
  1074. states.setFlag(i->first,&PlayerStatus::makingTurn,true);
  1075. gs->currentPlayer = i->first;
  1076. *connections[i->first] << ui16(100) << i->first;
  1077. //wait till turn is done
  1078. boost::unique_lock<boost::mutex> lock(states.mx);
  1079. while(states.players[i->first].makingTurn && !end2)
  1080. {
  1081. boost::posix_time::time_duration p;
  1082. p = boost::posix_time::milliseconds(200);
  1083. #ifdef _MSC_VER
  1084. states.cv.timed_wait(lock,p);
  1085. #else
  1086. boost::xtime time={0,0};
  1087. time.nsec = static_cast<boost::xtime::xtime_nsec_t>(p.total_nanoseconds());
  1088. states.cv.timed_wait(lock,time);
  1089. #endif
  1090. }
  1091. }
  1092. }
  1093. }
  1094. void CGameHandler::setupBattle( BattleInfo * curB, int3 tile, CCreatureSet &army1, CCreatureSet &army2, CGHeroInstance * hero1, CGHeroInstance * hero2 )
  1095. {
  1096. battleResult.set(NULL);
  1097. std::vector<CStack*> & stacks = (curB->stacks);
  1098. curB->tile = tile;
  1099. curB->siege = 0; //TODO: add sieges
  1100. curB->army1=army1;
  1101. curB->army2=army2;
  1102. curB->hero1=(hero1)?(hero1->id):(-1);
  1103. curB->hero2=(hero2)?(hero2->id):(-1);
  1104. curB->side1=(hero1)?(hero1->tempOwner):(-1);
  1105. curB->side2=(hero2)?(hero2->tempOwner):(-1);
  1106. curB->round = -2;
  1107. curB->activeStack = -1;
  1108. for(std::map<si32,std::pair<ui32,si32> >::iterator i = army1.slots.begin(); i!=army1.slots.end(); i++)
  1109. {
  1110. stacks.push_back(new CStack(&VLC->creh->creatures[i->second.first],i->second.second,hero1->tempOwner, stacks.size(), true,i->first));
  1111. stacks[stacks.size()-1]->ID = stacks.size()-1;
  1112. }
  1113. //initialization of positions
  1114. switch(army1.slots.size()) //for attacker
  1115. {
  1116. case 0:
  1117. break;
  1118. case 1:
  1119. stacks[0]->position = 86; //6
  1120. break;
  1121. case 2:
  1122. stacks[0]->position = 35; //3
  1123. stacks[1]->position = 137; //9
  1124. break;
  1125. case 3:
  1126. stacks[0]->position = 35; //3
  1127. stacks[1]->position = 86; //6
  1128. stacks[2]->position = 137; //9
  1129. break;
  1130. case 4:
  1131. stacks[0]->position = 1; //1
  1132. stacks[1]->position = 69; //5
  1133. stacks[2]->position = 103; //7
  1134. stacks[3]->position = 171; //11
  1135. break;
  1136. case 5:
  1137. stacks[0]->position = 1; //1
  1138. stacks[1]->position = 35; //3
  1139. stacks[2]->position = 86; //6
  1140. stacks[3]->position = 137; //9
  1141. stacks[4]->position = 171; //11
  1142. break;
  1143. case 6:
  1144. stacks[0]->position = 1; //1
  1145. stacks[1]->position = 35; //3
  1146. stacks[2]->position = 69; //5
  1147. stacks[3]->position = 103; //7
  1148. stacks[4]->position = 137; //9
  1149. stacks[5]->position = 171; //11
  1150. break;
  1151. case 7:
  1152. stacks[0]->position = 1; //1
  1153. stacks[1]->position = 35; //3
  1154. stacks[2]->position = 69; //5
  1155. stacks[3]->position = 86; //6
  1156. stacks[4]->position = 103; //7
  1157. stacks[5]->position = 137; //9
  1158. stacks[6]->position = 171; //11
  1159. break;
  1160. default: //fault
  1161. break;
  1162. }
  1163. for(std::map<si32,std::pair<ui32,si32> >::iterator i = army2.slots.begin(); i!=army2.slots.end(); i++)
  1164. stacks.push_back(new CStack(&VLC->creh->creatures[i->second.first],i->second.second,hero2 ? hero2->tempOwner : 255, stacks.size(), false, i->first));
  1165. switch(army2.slots.size()) //for defender
  1166. {
  1167. case 0:
  1168. break;
  1169. case 1:
  1170. stacks[0+army1.slots.size()]->position = 100; //6
  1171. break;
  1172. case 2:
  1173. stacks[0+army1.slots.size()]->position = 49; //3
  1174. stacks[1+army1.slots.size()]->position = 151; //9
  1175. break;
  1176. case 3:
  1177. stacks[0+army1.slots.size()]->position = 49; //3
  1178. stacks[1+army1.slots.size()]->position = 100; //6
  1179. stacks[2+army1.slots.size()]->position = 151; //9
  1180. break;
  1181. case 4:
  1182. stacks[0+army1.slots.size()]->position = 15; //1
  1183. stacks[1+army1.slots.size()]->position = 83; //5
  1184. stacks[2+army1.slots.size()]->position = 117; //7
  1185. stacks[3+army1.slots.size()]->position = 185; //11
  1186. break;
  1187. case 5:
  1188. stacks[0+army1.slots.size()]->position = 15; //1
  1189. stacks[1+army1.slots.size()]->position = 49; //3
  1190. stacks[2+army1.slots.size()]->position = 100; //6
  1191. stacks[3+army1.slots.size()]->position = 151; //9
  1192. stacks[4+army1.slots.size()]->position = 185; //11
  1193. break;
  1194. case 6:
  1195. stacks[0+army1.slots.size()]->position = 15; //1
  1196. stacks[1+army1.slots.size()]->position = 49; //3
  1197. stacks[2+army1.slots.size()]->position = 83; //5
  1198. stacks[3+army1.slots.size()]->position = 117; //7
  1199. stacks[4+army1.slots.size()]->position = 151; //9
  1200. stacks[5+army1.slots.size()]->position = 185; //11
  1201. break;
  1202. case 7:
  1203. stacks[0+army1.slots.size()]->position = 15; //1
  1204. stacks[1+army1.slots.size()]->position = 49; //3
  1205. stacks[2+army1.slots.size()]->position = 83; //5
  1206. stacks[3+army1.slots.size()]->position = 100; //6
  1207. stacks[4+army1.slots.size()]->position = 117; //7
  1208. stacks[5+army1.slots.size()]->position = 151; //9
  1209. stacks[6+army1.slots.size()]->position = 185; //11
  1210. break;
  1211. default: //fault
  1212. break;
  1213. }
  1214. for(unsigned g=0; g<stacks.size(); ++g) //shifting positions of two-hex creatures
  1215. {
  1216. if((stacks[g]->position%17)==1 && stacks[g]->creature->isDoubleWide())
  1217. {
  1218. stacks[g]->position += 1;
  1219. }
  1220. else if((stacks[g]->position%17)==15 && stacks[g]->creature->isDoubleWide())
  1221. {
  1222. stacks[g]->position -= 1;
  1223. }
  1224. }
  1225. std::stable_sort(stacks.begin(),stacks.end(),cmpst);
  1226. //block engaged players
  1227. if(hero1->tempOwner<PLAYER_LIMIT)
  1228. states.setFlag(hero1->tempOwner,&PlayerStatus::engagedIntoBattle,true);
  1229. if(hero2 && hero2->tempOwner<PLAYER_LIMIT)
  1230. states.setFlag(hero2->tempOwner,&PlayerStatus::engagedIntoBattle,true);
  1231. //send info about battles
  1232. BattleStart bs;
  1233. bs.info = curB;
  1234. sendAndApply(&bs);
  1235. }
  1236. void CGameHandler::checkForBattleEnd( std::vector<CStack*> &stacks )
  1237. {
  1238. //checking winning condition
  1239. bool hasStack[2]; //hasStack[0] - true if attacker has a living stack; defender similarily
  1240. hasStack[0] = hasStack[1] = false;
  1241. for(int b = 0; b<stacks.size(); ++b)
  1242. {
  1243. if(stacks[b]->alive)
  1244. {
  1245. hasStack[1-stacks[b]->attackerOwned] = true;
  1246. }
  1247. }
  1248. if(!hasStack[0] || !hasStack[1]) //somebody has won
  1249. {
  1250. BattleResult *br = new BattleResult;
  1251. br->result = 0;
  1252. br->winner = hasStack[1]; //fleeing side loses
  1253. gs->curB->calculateCasualties(br->casualties);
  1254. battleResult.set(br);
  1255. }
  1256. }