CGameHandler.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907
  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 "../CLua.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. #include <boost/thread/xtime.hpp>
  22. extern bool end2;
  23. #include "../lib/BattleAction.h"
  24. #ifdef min
  25. #undef min
  26. #endif
  27. #ifdef max
  28. #undef max
  29. #endif
  30. #define NEW_ROUND BattleNextRound bnr;\
  31. bnr.round = gs->curB->round + 1;\
  32. sendAndApply(&bnr);
  33. boost::condition_variable cTurn;
  34. boost::mutex mTurn;
  35. boost::shared_mutex gsm;
  36. CondSh<bool> battleMadeAction;
  37. CondSh<BattleResult *> battleResult(NULL);
  38. class CMP_stack
  39. {
  40. public:
  41. bool operator ()(const CStack* a, const CStack* b)
  42. {
  43. return (a->creature->speed)>(b->creature->speed);
  44. }
  45. } cmpst ;
  46. double distance(int3 a, int3 b)
  47. {
  48. return std::sqrt( (double)(a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y) );
  49. }
  50. //bool CGameState::checkFunc(int obid, std::string name)
  51. //{
  52. // if (objscr.find(obid)!=objscr.end())
  53. // {
  54. // if(objscr[obid].find(name)!=objscr[obid].end())
  55. // {
  56. // return true;
  57. // }
  58. // }
  59. // return false;
  60. //}
  61. void CGameHandler::handleCPPObjS(std::map<int,CCPPObjectScript*> * mapa, CCPPObjectScript * script)
  62. {
  63. std::vector<int> tempv = script->yourObjects();
  64. for (unsigned i=0;i<tempv.size();i++)
  65. {
  66. (*mapa)[tempv[i]]=script;
  67. }
  68. cppscripts.insert(script);
  69. }
  70. void CGameHandler::changePrimSkill(int ID, int which, int val, bool abs)
  71. {
  72. SetPrimSkill sps;
  73. sps.id = ID;
  74. sps.which = which;
  75. sps.abs = abs;
  76. sps.val = val;
  77. sendAndApply(&sps);
  78. if(which==4)
  79. {
  80. CGHeroInstance *hero = static_cast<CGHeroInstance *>(gs->map->objects[ID]);
  81. if(hero->exp >= VLC->heroh->reqExp(hero->level+1)) //new level
  82. {
  83. //hero->level++;
  84. //give prim skill
  85. std::cout << hero->name <<" got level "<<hero->level<<std::endl;
  86. int r = rand()%100, pom=0, x=0;
  87. int std::pair<int,int>::*g = (hero->level>9) ? (&std::pair<int,int>::second) : (&std::pair<int,int>::first);
  88. for(;x<PRIMARY_SKILLS;x++)
  89. {
  90. pom += hero->type->heroClass->primChance[x].*g;
  91. if(r<pom)
  92. break;
  93. }
  94. std::cout << "Bohater dostaje umiejetnosc pierwszorzedna " << x << " (wynik losowania "<<r<<")"<<std::endl;
  95. SetPrimSkill sps;
  96. sps.id = ID;
  97. sps.which = x;
  98. sps.abs = false;
  99. sps.val = 1;
  100. sendAndApply(&sps);
  101. hero->primSkills[x]++;
  102. std::set<ui16> choice;
  103. std::set<int> basicAndAdv, expert, none;
  104. for(int i=0;i<SKILL_QUANTITY;i++) none.insert(i);
  105. for(unsigned i=0;i<hero->secSkills.size();i++)
  106. {
  107. if(hero->secSkills[i].second < 2)
  108. basicAndAdv.insert(hero->secSkills[i].first);
  109. else
  110. expert.insert(hero->secSkills[i].first);
  111. none.erase(hero->secSkills[i].first);
  112. }
  113. if(hero->secSkills.size() < hero->type->heroClass->skillLimit) //free skill slot
  114. {
  115. choice.insert(hero->type->heroClass->chooseSecSkill(none)); //new skill
  116. }
  117. else
  118. {
  119. int s = hero->type->heroClass->chooseSecSkill(basicAndAdv);
  120. choice.insert(s);
  121. basicAndAdv.erase(s);
  122. }
  123. if(basicAndAdv.size())
  124. {
  125. choice.insert(hero->type->heroClass->chooseSecSkill(basicAndAdv)); //new skill
  126. }
  127. else if(hero->secSkills.size() < hero->type->heroClass->skillLimit)
  128. {
  129. choice.insert(hero->type->heroClass->chooseSecSkill(none)); //new skill
  130. }
  131. }
  132. //TODO - powiadomic interfejsy, sprawdzic czy nie ma awansu itp
  133. }
  134. }
  135. void CGameHandler::startBattle(CCreatureSet army1, CCreatureSet army2, int3 tile, CGHeroInstance *hero1, CGHeroInstance *hero2)
  136. {
  137. BattleInfo *curB = new BattleInfo;
  138. //battle start
  139. {
  140. battleResult.set(NULL);
  141. std::vector<CStack*> & stacks = (curB->stacks);
  142. curB->army1=army1;
  143. curB->army2=army2;
  144. curB->hero1=(hero1)?(hero1->id):(-1);
  145. curB->hero2=(hero1)?(hero1->id):(-1);
  146. curB->side1=(hero1)?(hero1->tempOwner):(-1);
  147. curB->side2=(hero2)?(hero2->tempOwner):(-1);
  148. curB->round = -2;
  149. curB->activeStack = -1;
  150. for(std::map<si32,std::pair<ui32,si32> >::iterator i = army1.slots.begin(); i!=army1.slots.end(); i++)
  151. {
  152. stacks.push_back(new CStack(&VLC->creh->creatures[i->second.first],i->second.second,hero1->tempOwner, stacks.size(), true));
  153. stacks[stacks.size()-1]->ID = stacks.size()-1;
  154. }
  155. //initialization of positions
  156. switch(army1.slots.size()) //for attacker
  157. {
  158. case 0:
  159. break;
  160. case 1:
  161. stacks[0]->position = 86; //6
  162. break;
  163. case 2:
  164. stacks[0]->position = 35; //3
  165. stacks[1]->position = 137; //9
  166. break;
  167. case 3:
  168. stacks[0]->position = 35; //3
  169. stacks[1]->position = 86; //6
  170. stacks[2]->position = 137; //9
  171. break;
  172. case 4:
  173. stacks[0]->position = 1; //1
  174. stacks[1]->position = 69; //5
  175. stacks[2]->position = 103; //7
  176. stacks[3]->position = 171; //11
  177. break;
  178. case 5:
  179. stacks[0]->position = 1; //1
  180. stacks[1]->position = 35; //3
  181. stacks[2]->position = 86; //6
  182. stacks[3]->position = 137; //9
  183. stacks[4]->position = 171; //11
  184. break;
  185. case 6:
  186. stacks[0]->position = 1; //1
  187. stacks[1]->position = 35; //3
  188. stacks[2]->position = 69; //5
  189. stacks[3]->position = 103; //7
  190. stacks[4]->position = 137; //9
  191. stacks[5]->position = 171; //11
  192. break;
  193. case 7:
  194. stacks[0]->position = 1; //1
  195. stacks[1]->position = 35; //3
  196. stacks[2]->position = 69; //5
  197. stacks[3]->position = 86; //6
  198. stacks[4]->position = 103; //7
  199. stacks[5]->position = 137; //9
  200. stacks[6]->position = 171; //11
  201. break;
  202. default: //fault
  203. break;
  204. }
  205. for(std::map<si32,std::pair<ui32,si32> >::iterator i = army2.slots.begin(); i!=army2.slots.end(); i++)
  206. stacks.push_back(new CStack(&VLC->creh->creatures[i->second.first],i->second.second,hero2 ? hero2->tempOwner : 255, stacks.size(), false));
  207. switch(army2.slots.size()) //for defender
  208. {
  209. case 0:
  210. break;
  211. case 1:
  212. stacks[0+army1.slots.size()]->position = 100; //6
  213. break;
  214. case 2:
  215. stacks[0+army1.slots.size()]->position = 49; //3
  216. stacks[1+army1.slots.size()]->position = 151; //9
  217. break;
  218. case 3:
  219. stacks[0+army1.slots.size()]->position = 49; //3
  220. stacks[1+army1.slots.size()]->position = 100; //6
  221. stacks[2+army1.slots.size()]->position = 151; //9
  222. break;
  223. case 4:
  224. stacks[0+army1.slots.size()]->position = 15; //1
  225. stacks[1+army1.slots.size()]->position = 83; //5
  226. stacks[2+army1.slots.size()]->position = 117; //7
  227. stacks[3+army1.slots.size()]->position = 185; //11
  228. break;
  229. case 5:
  230. stacks[0+army1.slots.size()]->position = 15; //1
  231. stacks[1+army1.slots.size()]->position = 49; //3
  232. stacks[2+army1.slots.size()]->position = 100; //6
  233. stacks[3+army1.slots.size()]->position = 151; //9
  234. stacks[4+army1.slots.size()]->position = 185; //11
  235. break;
  236. case 6:
  237. stacks[0+army1.slots.size()]->position = 15; //1
  238. stacks[1+army1.slots.size()]->position = 49; //3
  239. stacks[2+army1.slots.size()]->position = 83; //5
  240. stacks[3+army1.slots.size()]->position = 117; //7
  241. stacks[4+army1.slots.size()]->position = 151; //9
  242. stacks[5+army1.slots.size()]->position = 185; //11
  243. break;
  244. case 7:
  245. stacks[0+army1.slots.size()]->position = 15; //1
  246. stacks[1+army1.slots.size()]->position = 49; //3
  247. stacks[2+army1.slots.size()]->position = 83; //5
  248. stacks[3+army1.slots.size()]->position = 100; //6
  249. stacks[4+army1.slots.size()]->position = 117; //7
  250. stacks[5+army1.slots.size()]->position = 151; //9
  251. stacks[6+army1.slots.size()]->position = 185; //11
  252. break;
  253. default: //fault
  254. break;
  255. }
  256. for(unsigned g=0; g<stacks.size(); ++g) //shifting positions of two-hex creatures
  257. {
  258. if((stacks[g]->position%17)==1 && stacks[g]->creature->isDoubleWide())
  259. {
  260. stacks[g]->position += 1;
  261. }
  262. else if((stacks[g]->position%17)==15 && stacks[g]->creature->isDoubleWide())
  263. {
  264. stacks[g]->position -= 1;
  265. }
  266. }
  267. std::stable_sort(stacks.begin(),stacks.end(),cmpst);
  268. //block engaged players
  269. if(hero1->tempOwner<PLAYER_LIMIT)
  270. states[hero1->tempOwner] += 10;
  271. if(hero2 && hero2->tempOwner<PLAYER_LIMIT)
  272. states[hero2->tempOwner] += 10;
  273. //send info about battles
  274. BattleStart bs;
  275. bs.info = curB;
  276. sendAndApply(&bs);
  277. NEW_ROUND;
  278. }
  279. //tactic round
  280. {
  281. NEW_ROUND;
  282. if( (hero1 && hero1->getSecSkillLevel(19)>=0) ||
  283. ( hero2 && hero2->getSecSkillLevel(19)>=0) )//someone has tactics
  284. {
  285. //TODO: tactic round (round -1)
  286. }
  287. }
  288. //main loop
  289. while(!battleResult.get()) //till the end of the battle ;]
  290. {
  291. NEW_ROUND;
  292. std::vector<CStack*> & stacks = (gs->curB->stacks);
  293. const BattleInfo & curB = *gs->curB;
  294. //stack loop
  295. for(unsigned i=0;i<stacks.size() && !battleResult.get();i++)
  296. {
  297. if(!stacks[i]->alive) continue;//indicates imposiibility of making action for this dead unit
  298. BattleSetActiveStack sas;
  299. sas.stack = stacks[i]->ID;
  300. sendAndApply(&sas);
  301. //wait for response about battle action
  302. boost::unique_lock<boost::mutex> lock(battleMadeAction.mx);
  303. while(!battleMadeAction.data)
  304. battleMadeAction.cond.wait(lock);
  305. battleMadeAction.data = false;
  306. }
  307. }
  308. //end battle, remove all info, free memory
  309. sendAndApply(battleResult.data);
  310. delete battleResult.data;
  311. //for(int i=0;i<stacks.size();i++)
  312. // delete stacks[i];
  313. //delete curB;
  314. //curB = NULL;
  315. }
  316. void CGameHandler::handleConnection(std::set<int> players, CConnection &c)
  317. {
  318. try
  319. {
  320. ui16 pom;
  321. while(!end2)
  322. {
  323. c >> pom;
  324. bool blockvis = false;
  325. switch(pom)
  326. {
  327. case 100: //my interface ended its turn
  328. {
  329. mTurn.lock();
  330. states[gs->currentPlayer] = 0;
  331. mTurn.unlock();
  332. cTurn.notify_all();
  333. break;
  334. }
  335. case 500:
  336. {
  337. si32 id;
  338. c >> id;
  339. RemoveHero rh(id);
  340. sendAndApply(&rh);
  341. break;
  342. }
  343. case 501://interface wants to move hero
  344. {
  345. int3 start, end;
  346. si32 id;
  347. c >> id >> start >> end;
  348. int3 hmpos = end + int3(-1,0,0);
  349. TerrainTile t = gs->map->terrain[hmpos.x][hmpos.y][hmpos.z];
  350. CGHeroInstance *h = static_cast<CGHeroInstance *>(gs->map->objects[id]);
  351. int cost = (int)((double)h->getTileCost(t.tertype,t.malle,t.nuine) * distance(start,end));
  352. TryMoveHero tmh;
  353. tmh.id = id;
  354. tmh.start = start;
  355. tmh.end = end;
  356. tmh.result = 0;
  357. tmh.movePoints = h->movement;
  358. if((h->getOwner() != gs->currentPlayer) || //not turn of that hero
  359. (distance(start,end)>=1.5) || //tiles are not neighouring
  360. (h->movement < cost) || //lack of movement points
  361. (t.tertype == rock) || //rock
  362. (!h->canWalkOnSea() && t.tertype == water) ||
  363. (t.blocked && !t.visitable) ) //tile is blocked andnot visitable
  364. goto fail;
  365. //check if there is blocking visitable object
  366. blockvis = false;
  367. tmh.movePoints = h->movement = (h->movement-cost); //take move points
  368. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  369. {
  370. if(obj->blockVisit)
  371. {
  372. blockvis = true;
  373. break;
  374. }
  375. }
  376. //we start moving
  377. if(blockvis)//interaction with blocking object (like resources)
  378. {
  379. sendAndApply(&tmh); //failed to move to that tile but we visit object
  380. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  381. {
  382. if (obj->blockVisit)
  383. {
  384. //if(gs->checkFunc(obj->ID,"heroVisit")) //script function
  385. // gs->objscr[obj->ID]["heroVisit"]->onHeroVisit(obj,h->subID);
  386. if(obj->state) //hard-coded function
  387. obj->state->onHeroVisit(obj->id,h->subID);
  388. }
  389. }
  390. break;
  391. }
  392. else //normal move
  393. {
  394. tmh.result = 1;
  395. BOOST_FOREACH(CGObjectInstance *obj, gs->map->terrain[start.x][start.y][start.z].visitableObjects)
  396. {
  397. //TODO: allow to handle this in script-languages
  398. if(obj->state) //hard-coded function
  399. obj->state->onHeroLeave(obj->id,h->subID);
  400. }
  401. //reveal fog of war
  402. int heroSight = h->getSightDistance();
  403. int xbeg = start.x - heroSight - 2;
  404. if(xbeg < 0)
  405. xbeg = 0;
  406. int xend = start.x + heroSight + 2;
  407. if(xend >= gs->map->width)
  408. xend = gs->map->width;
  409. int ybeg = start.y - heroSight - 2;
  410. if(ybeg < 0)
  411. ybeg = 0;
  412. int yend = start.y + heroSight + 2;
  413. if(yend >= gs->map->height)
  414. yend = gs->map->height;
  415. for(int xd=xbeg; xd<xend; ++xd) //revealing part of map around heroes
  416. {
  417. for(int yd=ybeg; yd<yend; ++yd)
  418. {
  419. int deltaX = (hmpos.x-xd)*(hmpos.x-xd);
  420. int deltaY = (hmpos.y-yd)*(hmpos.y-yd);
  421. if(deltaX+deltaY<h->getSightDistance()*h->getSightDistance())
  422. {
  423. if(gs->players[h->getOwner()].fogOfWarMap[xd][yd][hmpos.z] == 0)
  424. {
  425. tmh.fowRevealed.insert(int3(xd,yd,hmpos.z));
  426. }
  427. }
  428. }
  429. }
  430. sendAndApply(&tmh);
  431. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)//call objects if they are visited
  432. {
  433. //if(gs->checkFunc(obj->ID,"heroVisit")) //script function
  434. // gs->objscr[obj->ID]["heroVisit"]->onHeroVisit(obj,h->subID);
  435. if(obj->state) //hard-coded function
  436. obj->state->onHeroVisit(obj->id,h->id);
  437. }
  438. }
  439. break;
  440. fail:
  441. sendAndApply(&tmh);
  442. break;
  443. }
  444. case 502: //swap creatures in garrison
  445. {
  446. ui8 what, p1, p2; si32 id1, id2;
  447. c >> what >> id1 >> p1 >> id2 >> p2;
  448. CArmedInstance *s1 = static_cast<CArmedInstance*>(gs->map->objects[id1]),
  449. *s2 = static_cast<CArmedInstance*>(gs->map->objects[id2]);
  450. CCreatureSet *S1 = &s1->army, *S2 = &s2->army;
  451. if(what==1) //swap
  452. {
  453. int pom = S2->slots[p2].first;
  454. S2->slots[p2].first = S1->slots[p1].first;
  455. S1->slots[p1].first = pom;
  456. int pom2 = S2->slots[p2].second;
  457. S2->slots[p2].second = S1->slots[p1].second;
  458. S1->slots[p1].second = pom2;
  459. if(!S1->slots[p1].first)
  460. S1->slots.erase(p1);
  461. if(!S2->slots[p2].first)
  462. S2->slots.erase(p2);
  463. }
  464. else if(what==2)//merge
  465. {
  466. if(S1->slots[p1].first != S2->slots[p2].first) break; //not same creature
  467. S2->slots[p2].second += S1->slots[p1].second;
  468. S1->slots[p1].first = NULL;
  469. S1->slots[p1].second = 0;
  470. S1->slots.erase(p1);
  471. }
  472. else if(what==3) //split
  473. {
  474. si32 val;
  475. c >> val;
  476. if(S2->slots.find(p2) != S2->slots.end()) break; //slot not free
  477. S2->slots[p2].first = S1->slots[p1].first;
  478. S2->slots[p2].second = val;
  479. S1->slots[p1].second -= val;
  480. if(!S1->slots[p1].second) //if we've moved all creatures
  481. S1->slots.erase(p1);
  482. }
  483. SetGarrisons sg;
  484. sg.garrs[id1] = *S1;
  485. if(s1 != s2)
  486. sg.garrs[id2] = *S2;
  487. sendAndApply(&sg);
  488. break;
  489. }
  490. case 503:
  491. {
  492. si32 id;
  493. ui8 pos;
  494. c >> id >> pos;
  495. CArmedInstance *s1 = static_cast<CArmedInstance*>(gs->map->objects[id]);
  496. s1->army.slots.erase(pos);
  497. SetGarrisons sg;
  498. sg.garrs[id] = s1->army;
  499. sendAndApply(&sg);
  500. break;
  501. }
  502. case 504:
  503. {
  504. si32 tid, bid;
  505. c >> tid >> bid;
  506. CGTownInstance * t = static_cast<CGTownInstance*>(gs->map->objects[tid]);
  507. CBuilding * b = VLC->buildh->buildings[t->subID][bid];
  508. for(int i=0;i<RESOURCE_QUANTITY;i++)
  509. if(b->resources[i] > gs->players[t->tempOwner].resources[i])
  510. break; //no res
  511. //TODO: check requirements
  512. //TODO: check if building isn't forbidden
  513. NewStructures ns;
  514. ns.tid = tid;
  515. if(bid>36) //upg dwelling
  516. {
  517. if(t->getHordeLevel(0) == (bid-37))
  518. ns.bid.insert(19);
  519. else if(t->getHordeLevel(1) == (bid-37))
  520. ns.bid.insert(25);
  521. }
  522. else if(bid >= 30) //bas. dwelling
  523. {
  524. SetStrInfo ssi;
  525. ssi.tid = tid;
  526. ssi.cres = t->strInfo.creatures;
  527. ssi.cres[bid-30] = VLC->creh->creatures[t->town->basicCreatures[bid-30]].growth;
  528. sendAndApply(&ssi);
  529. }
  530. ns.bid.insert(bid);
  531. ns.builded = t->builded + 1;
  532. sendAndApply(&ns);
  533. SetResources sr;
  534. sr.player = t->tempOwner;
  535. sr.res = gs->players[t->tempOwner].resources;
  536. for(int i=0;i<7;i++)
  537. sr.res[i]-=b->resources[i];
  538. sendAndApply(&sr);
  539. break;
  540. }
  541. case 3002:
  542. {
  543. BattleAction ba;
  544. c >> ba;
  545. switch(ba.actionType)
  546. {
  547. case 2: //walk
  548. {
  549. CStack *curStack = gs->curB->getStack(ba.stackNumber),
  550. *stackAtEnd = gs->curB->getStackT(ba.destinationTile);
  551. //initing necessary tables
  552. bool accessibility[187];
  553. if(curStack->creature->isDoubleWide())
  554. {
  555. gs->curB->getAccessibilityMapForTwoHex(accessibility,curStack->attackerOwned);
  556. accessibility[curStack->attackerOwned ? curStack->position+1 : curStack->position-1]=true;//OUR second tile is for US accessible
  557. }
  558. else
  559. gs->curB->getAccessibilityMap(accessibility);
  560. accessibility[curStack->position] = true; //OUR tile is for US accessible
  561. //if(!stackAtEnd && !accessibility[dest])
  562. // return false;
  563. //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
  564. // return false;
  565. std::vector<int> path = gs->curB->getPath(curStack->position,ba.destinationTile,accessibility);
  566. int tilesToMove = std::max((int)path.size()-curStack->creature->speed, 0);
  567. for(int v=path.size()-1; v>=tilesToMove; --v)
  568. {
  569. if(v!=0 || !stackAtEnd) //it's not the last step or the last tile is free
  570. {
  571. //inform clients about move
  572. BattleStackMoved sm;
  573. sm.stack = curStack->ID;
  574. sm.tile = path[v];
  575. if(v==path.size()-1)//move start - set flag
  576. sm.flags |= 1;
  577. if(v==0 || (stackAtEnd && v==1)) //move end - set flag
  578. sm.flags |= 2;
  579. sendAndApply(&sm);
  580. }
  581. else //if it's last step and we should attack unit at the end
  582. {
  583. //LOCPLINT->battleStackAttacking(ID, path[v]);
  584. ////counting dealt damage
  585. //int finalDmg = calculateDmg(curStack, curB->stacks[numberOfStackAtEnd]);
  586. ////applying damages
  587. //int cresKilled = finalDmg / curB->stacks[numberOfStackAtEnd]->creature->hitPoints;
  588. //int damageFirst = finalDmg % curB->stacks[numberOfStackAtEnd]->creature->hitPoints;
  589. //if( curB->stacks[numberOfStackAtEnd]->firstHPleft <= damageFirst )
  590. //{
  591. // curB->stacks[numberOfStackAtEnd]->amount -= 1;
  592. // curB->stacks[numberOfStackAtEnd]->firstHPleft += curB->stacks[numberOfStackAtEnd]->creature->hitPoints - damageFirst;
  593. //}
  594. //else
  595. //{
  596. // curB->stacks[numberOfStackAtEnd]->firstHPleft -= damageFirst;
  597. //}
  598. //int cresInstackBefore = curB->stacks[numberOfStackAtEnd]->amount;
  599. //curB->stacks[numberOfStackAtEnd]->amount -= cresKilled;
  600. //if(curB->stacks[numberOfStackAtEnd]->amount<=0) //stack killed
  601. //{
  602. // curB->stacks[numberOfStackAtEnd]->amount = 0;
  603. // LOCPLINT->battleStackKilled(curB->stacks[numberOfStackAtEnd]->ID, finalDmg, std::min(cresKilled, cresInstackBefore) , ID, false);
  604. // curB->stacks[numberOfStackAtEnd]->alive = false;
  605. //}
  606. //else
  607. //{
  608. // LOCPLINT->battleStackIsAttacked(curB->stacks[numberOfStackAtEnd]->ID, finalDmg, std::min(cresKilled, cresInstackBefore), ID, false);
  609. //}
  610. //damage applied
  611. }
  612. }
  613. //curB->stackActionPerformed = true;
  614. //LOCPLINT->actionFinished(BattleAction());
  615. break;
  616. }
  617. case 3: //defend
  618. {
  619. break;
  620. }
  621. case 4: //retreat/flee
  622. {
  623. //TODO: check if fleeing is possible (e.g. enemy may have Shackles of War)
  624. //TODO: calculate casualties
  625. //TODO: remove retreating hero from map and place it in recrutation list
  626. BattleResult *br = new BattleResult;
  627. br->result = 1;
  628. battleResult.set(br);
  629. break;
  630. }
  631. case 6: //walk or attack
  632. {
  633. //battleMoveCreatureStack(ba.stackNumber, ba.destinationTile);
  634. //battleAttackCreatureStack(ba.stackNumber, ba.destinationTile);
  635. break;
  636. }
  637. case 7: //shoot
  638. {
  639. //battleShootCreatureStack(ba.stackNumber, ba.destinationTile);
  640. break;
  641. }
  642. }
  643. battleMadeAction.setn(true);
  644. //sprawdzic czy po tej akcji ktoras strona nie wygrala bitwy
  645. break;
  646. }
  647. default:
  648. #ifndef __GNUC__
  649. throw std::exception("Not supported client message!");
  650. #else
  651. throw std::exception();
  652. #endif
  653. break;
  654. }
  655. }
  656. }
  657. catch (const std::exception& e)
  658. {
  659. std::cerr << e.what() << std::endl;
  660. end2 = true;
  661. }
  662. catch (const std::exception * e)
  663. {
  664. std::cerr << e->what()<< std::endl;
  665. end2 = true;
  666. delete e;
  667. }
  668. catch(...)
  669. {
  670. end2 = true;
  671. }
  672. }
  673. CGameHandler::CGameHandler(void)
  674. {
  675. gs = NULL;
  676. }
  677. CGameHandler::~CGameHandler(void)
  678. {
  679. delete gs;
  680. }
  681. void CGameHandler::init(StartInfo *si, int Seed)
  682. {
  683. Mapa *map = new Mapa(si->mapname);
  684. gs = new CGameState();
  685. gs->init(si,map,Seed);
  686. /****************************LUA OBJECT SCRIPTS************************************************/
  687. //std::vector<std::string> * lf = CLuaHandler::searchForScripts("scripts/lua/objects"); //files
  688. //for (int i=0; i<lf->size(); i++)
  689. //{
  690. // try
  691. // {
  692. // std::vector<std::string> * temp = CLuaHandler::functionList((*lf)[i]);
  693. // CLuaObjectScript * objs = new CLuaObjectScript((*lf)[i]);
  694. // CLuaCallback::registerFuncs(objs->is);
  695. // //objs
  696. // for (int j=0; j<temp->size(); j++)
  697. // {
  698. // int obid ; //obj ID
  699. // int dspos = (*temp)[j].find_first_of('_');
  700. // obid = atoi((*temp)[j].substr(dspos+1,(*temp)[j].size()-dspos-1).c_str());
  701. // std::string fname = (*temp)[j].substr(0,dspos);
  702. // if (skrypty->find(obid)==skrypty->end())
  703. // skrypty->insert(std::pair<int, std::map<std::string, CObjectScript*> >(obid,std::map<std::string,CObjectScript*>()));
  704. // (*skrypty)[obid].insert(std::pair<std::string, CObjectScript*>(fname,objs));
  705. // }
  706. // delete temp;
  707. // }HANDLE_EXCEPTION
  708. //}
  709. //delete lf;
  710. }
  711. int lowestSpeed(CGHeroInstance * chi)
  712. {
  713. std::map<si32,std::pair<ui32,si32> >::iterator i = chi->army.slots.begin();
  714. int ret = VLC->creh->creatures[(*i++).second.first].speed;
  715. for (;i!=chi->army.slots.end();i++)
  716. {
  717. ret = std::min(ret,VLC->creh->creatures[(*i).second.first].speed);
  718. }
  719. return ret;
  720. }
  721. int valMovePoints(CGHeroInstance * chi)
  722. {
  723. int ret = 1270+70*lowestSpeed(chi);
  724. if (ret>2000)
  725. ret=2000;
  726. //TODO: additional bonuses (but they aren't currently stored in chi)
  727. return ret;
  728. }
  729. void CGameHandler::newTurn()
  730. {
  731. NewTurn n;
  732. n.day = gs->day + 1;
  733. for ( std::map<ui8, PlayerState>::iterator i=gs->players.begin() ; i!=gs->players.end();i++)
  734. {
  735. if(i->first>=PLAYER_LIMIT) continue;
  736. NewTurn::Resources r;
  737. r.player = i->first;
  738. for(int j=0;j<RESOURCE_QUANTITY;j++)
  739. r.resources[j] = i->second.resources[j];
  740. for (unsigned j=0;j<(*i).second.heroes.size();j++) //handle heroes
  741. {
  742. NewTurn::Hero h;
  743. h.id = (*i).second.heroes[j]->id;
  744. h.move = valMovePoints((*i).second.heroes[j]);
  745. h.mana = (*i).second.heroes[j]->mana;
  746. n.heroes.insert(h);
  747. }
  748. for(unsigned j=0;j<i->second.towns.size();j++)//handle towns
  749. {
  750. i->second.towns[j]->builded=0;
  751. //if(gs->getDate(1)==1) //first day of week
  752. //{
  753. // for(int k=0;k<CREATURES_PER_TOWN;k++) //creature growths
  754. // {
  755. // if(i->second.towns[j]->creatureDwelling(k))//there is dwelling (k-level)
  756. // i->second.towns[j]->strInfo.creatures[k]+=i->second.towns[j]->creatureGrowth(k);
  757. // }
  758. //}
  759. if((gs->day) && i->first<PLAYER_LIMIT)//not the first day and town not neutral
  760. r.resources[6] += i->second.towns[j]->dailyIncome();
  761. }
  762. n.res.insert(r);
  763. }
  764. sendAndApply(&n);
  765. for (std::set<CCPPObjectScript *>::iterator i=cppscripts.begin();i!=cppscripts.end();i++)
  766. {
  767. (*i)->newTurn();
  768. }
  769. }
  770. void CGameHandler::run()
  771. {
  772. BOOST_FOREACH(CConnection *cc, conns)
  773. {//init conn.
  774. ui8 quantity, pom;
  775. //ui32 seed;
  776. (*cc) << gs->scenarioOps->mapname << gs->map->checksum << gs->seed;
  777. (*cc) >> quantity;
  778. for(int i=0;i<quantity;i++)
  779. {
  780. (*cc) >> pom;
  781. gsm.lock();
  782. connections[pom] = cc;
  783. gsm.unlock();
  784. }
  785. }
  786. for(std::set<CConnection*>::iterator i = conns.begin(); i!=conns.end();i++)
  787. {
  788. std::set<int> pom;
  789. for(std::map<int,CConnection*>::iterator j = connections.begin(); j!=connections.end();j++)
  790. if(j->second == *i)
  791. pom.insert(j->first);
  792. boost::thread(boost::bind(&CGameHandler::handleConnection,this,pom,boost::ref(**i)));
  793. }
  794. /****************************SCRIPTS************************************************/
  795. //std::map<int, std::map<std::string, CObjectScript*> > * skrypty = &objscr; //alias for easier access
  796. /****************************C++ OBJECT SCRIPTS************************************************/
  797. std::map<int,CCPPObjectScript*> scripts;
  798. CScriptCallback * csc = new CScriptCallback();
  799. csc->gh = this;
  800. handleCPPObjS(&scripts,new CVisitableOPH(csc));
  801. handleCPPObjS(&scripts,new CVisitableOPW(csc));
  802. handleCPPObjS(&scripts,new CPickable(csc));
  803. handleCPPObjS(&scripts,new CMines(csc));
  804. handleCPPObjS(&scripts,new CTownScript(csc));
  805. handleCPPObjS(&scripts,new CHeroScript(csc));
  806. handleCPPObjS(&scripts,new CMonsterS(csc));
  807. handleCPPObjS(&scripts,new CCreatureGen(csc));
  808. /****************************INITIALIZING OBJECT SCRIPTS************************************************/
  809. //std::string temps("newObject");
  810. for (unsigned i=0; i<gs->map->objects.size(); i++)
  811. {
  812. //c++ scripts
  813. if (scripts.find(gs->map->objects[i]->ID) != scripts.end())
  814. {
  815. gs->map->objects[i]->state = scripts[gs->map->objects[i]->ID];
  816. gs->map->objects[i]->state->newObject(gs->map->objects[i]->id);
  817. }
  818. else
  819. {
  820. gs->map->objects[i]->state = NULL;
  821. }
  822. //// lua scripts
  823. //if(checkFunc(map->objects[i]->ID,temps))
  824. // (*skrypty)[map->objects[i]->ID][temps]->newObject(map->objects[i]);
  825. }
  826. while (!end2)
  827. {
  828. newTurn();
  829. for(std::map<ui8,PlayerState>::iterator i = gs->players.begin(); i != gs->players.end(); i++)
  830. {
  831. 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
  832. states[i->first] = 1;
  833. gs->currentPlayer = i->first;
  834. *connections[i->first] << ui16(100) << i->first;
  835. //wait till turn is done
  836. boost::unique_lock<boost::mutex> lock(mTurn);
  837. while(states[i->first] && !end2)
  838. {
  839. boost::posix_time::time_duration p;
  840. p= boost::posix_time::seconds(1);
  841. boost::xtime time={0,0};
  842. time.sec = static_cast<boost::xtime::xtime_sec_t>(p.total_seconds());
  843. cTurn.timed_wait(lock,time);
  844. }
  845. }
  846. }
  847. }