PlayerMessageProcessor.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847
  1. /*
  2. * CGameHandler.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "PlayerMessageProcessor.h"
  12. #include "TurnOrderProcessor.h"
  13. #include "../CGameHandler.h"
  14. #include "../CVCMIServer.h"
  15. #include "../TurnTimerHandler.h"
  16. #include "../../lib/CHeroHandler.h"
  17. #include "../../lib/CPlayerState.h"
  18. #include "../../lib/StartInfo.h"
  19. #include "../../lib/entities/building/CBuilding.h"
  20. #include "../../lib/gameState/CGameState.h"
  21. #include "../../lib/mapObjects/CGTownInstance.h"
  22. #include "../../lib/mapObjects/CGHeroInstance.h"
  23. #include "../../lib/modding/IdentifierStorage.h"
  24. #include "../../lib/modding/ModScope.h"
  25. #include "../../lib/mapping/CMap.h"
  26. #include "../../lib/networkPacks/PacksForClient.h"
  27. #include "../../lib/networkPacks/StackLocation.h"
  28. #include "../../lib/serializer/Connection.h"
  29. PlayerMessageProcessor::PlayerMessageProcessor(CGameHandler * gameHandler)
  30. :gameHandler(gameHandler)
  31. {
  32. }
  33. void PlayerMessageProcessor::playerMessage(PlayerColor player, const std::string & message, ObjectInstanceID currObj)
  34. {
  35. if(!message.empty() && message[0] == '!')
  36. {
  37. broadcastMessage(player, message);
  38. handleCommand(player, message);
  39. return;
  40. }
  41. if(handleCheatCode(message, player, currObj))
  42. {
  43. if(!gameHandler->getPlayerSettings(player)->isControlledByAI())
  44. {
  45. MetaString txt;
  46. txt.appendLocalString(EMetaText::GENERAL_TXT, 260);
  47. broadcastSystemMessage(txt);
  48. }
  49. if(!player.isSpectator())
  50. gameHandler->checkVictoryLossConditionsForPlayer(player); //Player enter win code or got required art\creature
  51. return;
  52. }
  53. broadcastMessage(player, message);
  54. }
  55. void PlayerMessageProcessor::commandExit(PlayerColor player, const std::vector<std::string> & words)
  56. {
  57. bool isHost = gameHandler->gameLobby()->isPlayerHost(player);
  58. if(!isHost)
  59. return;
  60. broadcastSystemMessage("game was terminated");
  61. gameHandler->gameLobby()->setState(EServerState::SHUTDOWN);
  62. }
  63. void PlayerMessageProcessor::commandKick(PlayerColor player, const std::vector<std::string> & words)
  64. {
  65. bool isHost = gameHandler->gameLobby()->isPlayerHost(player);
  66. if(!isHost)
  67. return;
  68. if(words.size() == 2)
  69. {
  70. auto playername = words[1];
  71. PlayerColor playerToKick(PlayerColor::CANNOT_DETERMINE);
  72. if(std::all_of(playername.begin(), playername.end(), ::isdigit))
  73. playerToKick = PlayerColor(std::stoi(playername));
  74. else
  75. {
  76. for(auto & c : gameHandler->connections)
  77. {
  78. if(c.first.toString() == playername)
  79. playerToKick = c.first;
  80. }
  81. }
  82. if(playerToKick != PlayerColor::CANNOT_DETERMINE)
  83. {
  84. PlayerCheated pc;
  85. pc.player = playerToKick;
  86. pc.losingCheatCode = true;
  87. gameHandler->sendAndApply(&pc);
  88. gameHandler->checkVictoryLossConditionsForPlayer(playerToKick);
  89. }
  90. }
  91. }
  92. void PlayerMessageProcessor::commandSave(PlayerColor player, const std::vector<std::string> & words)
  93. {
  94. bool isHost = gameHandler->gameLobby()->isPlayerHost(player);
  95. if(!isHost)
  96. return;
  97. if(words.size() == 2)
  98. {
  99. gameHandler->save("Saves/" + words[1]);
  100. broadcastSystemMessage("game saved as " + words[1]);
  101. }
  102. }
  103. void PlayerMessageProcessor::commandCheaters(PlayerColor player, const std::vector<std::string> & words)
  104. {
  105. int playersCheated = 0;
  106. for(const auto & player : gameHandler->gameState()->players)
  107. {
  108. if(player.second.cheated)
  109. {
  110. broadcastSystemMessage("Player " + player.first.toString() + " is cheater!");
  111. playersCheated++;
  112. }
  113. }
  114. if(!playersCheated)
  115. broadcastSystemMessage("No cheaters registered!");
  116. }
  117. void PlayerMessageProcessor::commandHelp(PlayerColor player, const std::vector<std::string> & words)
  118. {
  119. broadcastSystemMessage("Available commands to host:");
  120. broadcastSystemMessage("'!exit' - immediately ends current game");
  121. broadcastSystemMessage("'!kick <player>' - kick specified player from the game");
  122. broadcastSystemMessage("'!save <filename>' - save game under specified filename");
  123. broadcastSystemMessage("Available commands to all players:");
  124. broadcastSystemMessage("'!help' - display this help");
  125. broadcastSystemMessage("'!cheaters' - list players that entered cheat command during game");
  126. broadcastSystemMessage("'!vote' - allows to change some game settings if all players vote for it");
  127. }
  128. void PlayerMessageProcessor::commandVote(PlayerColor player, const std::vector<std::string> & words)
  129. {
  130. if(words.size() < 2)
  131. {
  132. broadcastSystemMessage("'!vote simturns allow X' - allow simultaneous turns for specified number of days, or until contact");
  133. broadcastSystemMessage("'!vote simturns force X' - force simultaneous turns for specified number of days, blocking player contacts");
  134. broadcastSystemMessage("'!vote simturns abort' - abort simultaneous turns once this turn ends");
  135. broadcastSystemMessage("'!vote timer prolong X' - prolong base timer for all players by specified number of seconds");
  136. return;
  137. }
  138. if(words[1] == "yes" || words[1] == "no")
  139. {
  140. if(currentVote == ECurrentChatVote::NONE)
  141. {
  142. broadcastSystemMessage("No active voting!");
  143. return;
  144. }
  145. if(words[1] == "yes")
  146. {
  147. awaitingPlayers.erase(player);
  148. if(awaitingPlayers.empty())
  149. finishVoting();
  150. return;
  151. }
  152. if(words[1] == "no")
  153. {
  154. abortVoting();
  155. return;
  156. }
  157. }
  158. const auto & parseNumber = [](const std::string & input) -> std::optional<int>
  159. {
  160. try
  161. {
  162. return std::stol(input);
  163. }
  164. catch(std::logic_error &)
  165. {
  166. return std::nullopt;
  167. }
  168. };
  169. if(words[1] == "simturns" && words.size() > 2)
  170. {
  171. if(words[2] == "allow" && words.size() > 3)
  172. {
  173. auto daysCount = parseNumber(words[3]);
  174. if(daysCount && daysCount.value() > 0)
  175. startVoting(player, ECurrentChatVote::SIMTURNS_ALLOW, daysCount.value());
  176. return;
  177. }
  178. if(words[2] == "force" && words.size() > 3)
  179. {
  180. auto daysCount = parseNumber(words[3]);
  181. if(daysCount && daysCount.value() > 0)
  182. startVoting(player, ECurrentChatVote::SIMTURNS_FORCE, daysCount.value());
  183. return;
  184. }
  185. if(words[2] == "abort")
  186. {
  187. startVoting(player, ECurrentChatVote::SIMTURNS_ABORT, 0);
  188. return;
  189. }
  190. }
  191. if(words[1] == "timer" && words.size() > 2)
  192. {
  193. if(words[2] == "prolong" && words.size() > 3)
  194. {
  195. auto secondsCount = parseNumber(words[3]);
  196. if(secondsCount && secondsCount.value() > 0)
  197. startVoting(player, ECurrentChatVote::TIMER_PROLONG, secondsCount.value());
  198. return;
  199. }
  200. }
  201. broadcastSystemMessage("Voting command not recognized!");
  202. }
  203. void PlayerMessageProcessor::finishVoting()
  204. {
  205. switch(currentVote)
  206. {
  207. case ECurrentChatVote::SIMTURNS_ALLOW:
  208. broadcastSystemMessage("Voting successful. Simultaneous turns will run for " + std::to_string(currentVoteParameter) + " more days, or until contact");
  209. gameHandler->turnOrder->setMaxSimturnsDuration(currentVoteParameter);
  210. break;
  211. case ECurrentChatVote::SIMTURNS_FORCE:
  212. broadcastSystemMessage("Voting successful. Simultaneous turns will run for " + std::to_string(currentVoteParameter) + " more days. Contacts are blocked");
  213. gameHandler->turnOrder->setMinSimturnsDuration(currentVoteParameter);
  214. break;
  215. case ECurrentChatVote::SIMTURNS_ABORT:
  216. broadcastSystemMessage("Voting successful. Simultaneous turns will end on next day");
  217. gameHandler->turnOrder->setMinSimturnsDuration(0);
  218. gameHandler->turnOrder->setMaxSimturnsDuration(0);
  219. break;
  220. case ECurrentChatVote::TIMER_PROLONG:
  221. broadcastSystemMessage("Voting successful. Timer for all players has been prolonger for " + std::to_string(currentVoteParameter) + " seconds");
  222. gameHandler->turnTimerHandler->prolongTimers(currentVoteParameter * 1000);
  223. break;
  224. }
  225. currentVote = ECurrentChatVote::NONE;
  226. currentVoteParameter = -1;
  227. }
  228. void PlayerMessageProcessor::abortVoting()
  229. {
  230. broadcastSystemMessage("Player voted against change. Voting aborted");
  231. currentVote = ECurrentChatVote::NONE;
  232. }
  233. void PlayerMessageProcessor::startVoting(PlayerColor initiator, ECurrentChatVote what, int parameter)
  234. {
  235. currentVote = what;
  236. currentVoteParameter = parameter;
  237. switch(currentVote)
  238. {
  239. case ECurrentChatVote::SIMTURNS_ALLOW:
  240. broadcastSystemMessage("Started voting to allow simultaneous turns for " + std::to_string(parameter) + " more days");
  241. break;
  242. case ECurrentChatVote::SIMTURNS_FORCE:
  243. broadcastSystemMessage("Started voting to force simultaneous turns for " + std::to_string(parameter) + " more days");
  244. break;
  245. case ECurrentChatVote::SIMTURNS_ABORT:
  246. broadcastSystemMessage("Started voting to end simultaneous turns starting from next day");
  247. break;
  248. case ECurrentChatVote::TIMER_PROLONG:
  249. broadcastSystemMessage("Started voting to prolong timer for all players by " + std::to_string(parameter) + " seconds");
  250. break;
  251. default:
  252. return;
  253. }
  254. broadcastSystemMessage("Type '!vote yes' to agree to this change or '!vote no' to vote against it");
  255. awaitingPlayers.clear();
  256. for(PlayerColor player(0); player < PlayerColor::PLAYER_LIMIT; ++player)
  257. {
  258. auto state = gameHandler->getPlayerState(player, false);
  259. if(state && state->isHuman() && initiator != player)
  260. awaitingPlayers.insert(player);
  261. }
  262. if(awaitingPlayers.empty())
  263. finishVoting();
  264. }
  265. void PlayerMessageProcessor::handleCommand(PlayerColor player, const std::string & message)
  266. {
  267. if(message.empty() || message[0] != '!')
  268. return;
  269. std::vector<std::string> words;
  270. boost::split(words, message, boost::is_any_of(" "));
  271. if(words[0] == "!exit" || words[0] == "!quit")
  272. commandExit(player, words);
  273. if(words[0] == "!help")
  274. commandHelp(player, words);
  275. if(words[0] == "!vote")
  276. commandVote(player, words);
  277. if(words[0] == "!kick")
  278. commandKick(player, words);
  279. if(words[0] == "!save")
  280. commandSave(player, words);
  281. if(words[0] == "!cheaters")
  282. commandCheaters(player, words);
  283. }
  284. void PlayerMessageProcessor::cheatGiveSpells(PlayerColor player, const CGHeroInstance * hero)
  285. {
  286. if (!hero)
  287. return;
  288. ///Give hero spellbook
  289. if (!hero->hasSpellbook())
  290. gameHandler->giveHeroNewArtifact(hero, ArtifactID(ArtifactID::SPELLBOOK).toArtifact(), ArtifactPosition::SPELLBOOK);
  291. ///Give all spells with bonus (to allow banned spells)
  292. GiveBonus giveBonus(GiveBonus::ETarget::OBJECT);
  293. giveBonus.id = hero->id;
  294. giveBonus.bonus = Bonus(BonusDuration::PERMANENT, BonusType::SPELLS_OF_LEVEL, BonusSource::OTHER, 0, BonusSourceID());
  295. //start with level 0 to skip abilities
  296. for (int level = 1; level <= GameConstants::SPELL_LEVELS; level++)
  297. {
  298. giveBonus.bonus.subtype = BonusCustomSubtype::spellLevel(level);
  299. gameHandler->sendAndApply(&giveBonus);
  300. }
  301. ///Give mana
  302. SetMana sm;
  303. sm.hid = hero->id;
  304. sm.val = 999;
  305. sm.absolute = true;
  306. gameHandler->sendAndApply(&sm);
  307. }
  308. void PlayerMessageProcessor::cheatBuildTown(PlayerColor player, const CGTownInstance * town)
  309. {
  310. if (!town)
  311. return;
  312. for (auto & build : town->town->buildings)
  313. {
  314. if (!town->hasBuilt(build.first)
  315. && !build.second->getNameTranslated().empty()
  316. && build.first != BuildingID::SHIP)
  317. {
  318. gameHandler->buildStructure(town->id, build.first, true);
  319. }
  320. }
  321. }
  322. void PlayerMessageProcessor::cheatGiveArmy(PlayerColor player, const CGHeroInstance * hero, std::vector<std::string> words)
  323. {
  324. if (!hero)
  325. return;
  326. std::string creatureIdentifier = words.empty() ? "archangel" : words[0];
  327. std::optional<int> amountPerSlot;
  328. try
  329. {
  330. amountPerSlot = std::stol(words.at(1));
  331. }
  332. catch(std::logic_error&)
  333. {
  334. }
  335. std::optional<int32_t> creatureId = VLC->identifiers()->getIdentifier(ModScope::scopeGame(), "creature", creatureIdentifier, false);
  336. if(creatureId.has_value())
  337. {
  338. const auto * creature = CreatureID(creatureId.value()).toCreature();
  339. for (int i = 0; i < GameConstants::ARMY_SIZE; i++)
  340. {
  341. if (!hero->hasStackAtSlot(SlotID(i)))
  342. {
  343. if (amountPerSlot.has_value())
  344. gameHandler->insertNewStack(StackLocation(hero, SlotID(i)), creature, *amountPerSlot);
  345. else
  346. gameHandler->insertNewStack(StackLocation(hero, SlotID(i)), creature, 5 * std::pow(10, i));
  347. }
  348. }
  349. }
  350. }
  351. void PlayerMessageProcessor::cheatGiveMachines(PlayerColor player, const CGHeroInstance * hero)
  352. {
  353. if (!hero)
  354. return;
  355. if (!hero->getArt(ArtifactPosition::MACH1))
  356. gameHandler->giveHeroNewArtifact(hero, ArtifactID(ArtifactID::BALLISTA).toArtifact(), ArtifactPosition::MACH1);
  357. if (!hero->getArt(ArtifactPosition::MACH2))
  358. gameHandler->giveHeroNewArtifact(hero, ArtifactID(ArtifactID::AMMO_CART).toArtifact(), ArtifactPosition::MACH2);
  359. if (!hero->getArt(ArtifactPosition::MACH3))
  360. gameHandler->giveHeroNewArtifact(hero, ArtifactID(ArtifactID::FIRST_AID_TENT).toArtifact(), ArtifactPosition::MACH3);
  361. }
  362. void PlayerMessageProcessor::cheatGiveArtifacts(PlayerColor player, const CGHeroInstance * hero, std::vector<std::string> words)
  363. {
  364. if (!hero)
  365. return;
  366. if (!words.empty())
  367. {
  368. for (auto const & word : words)
  369. {
  370. auto artID = VLC->identifiers()->getIdentifier(ModScope::scopeGame(), "artifact", word, false);
  371. if(artID && VLC->arth->objects[*artID])
  372. gameHandler->giveHeroNewArtifact(hero, ArtifactID(*artID).toArtifact(), ArtifactPosition::FIRST_AVAILABLE);
  373. }
  374. }
  375. else
  376. {
  377. for(int g = 7; g < VLC->arth->objects.size(); ++g) //including artifacts from mods
  378. {
  379. if(VLC->arth->objects[g]->canBePutAt(hero))
  380. gameHandler->giveHeroNewArtifact(hero, ArtifactID(g).toArtifact(), ArtifactPosition::FIRST_AVAILABLE);
  381. }
  382. }
  383. }
  384. void PlayerMessageProcessor::cheatLevelup(PlayerColor player, const CGHeroInstance * hero, std::vector<std::string> words)
  385. {
  386. if (!hero)
  387. return;
  388. int levelsToGain;
  389. try
  390. {
  391. levelsToGain = std::stol(words.at(0));
  392. }
  393. catch(std::logic_error&)
  394. {
  395. levelsToGain = 1;
  396. }
  397. gameHandler->giveExperience(hero, VLC->heroh->reqExp(hero->level + levelsToGain) - VLC->heroh->reqExp(hero->level));
  398. }
  399. void PlayerMessageProcessor::cheatExperience(PlayerColor player, const CGHeroInstance * hero, std::vector<std::string> words)
  400. {
  401. if (!hero)
  402. return;
  403. int expAmountProcessed;
  404. try
  405. {
  406. expAmountProcessed = std::stol(words.at(0));
  407. }
  408. catch(std::logic_error&)
  409. {
  410. expAmountProcessed = 10000;
  411. }
  412. gameHandler->giveExperience(hero, expAmountProcessed);
  413. }
  414. void PlayerMessageProcessor::cheatMovement(PlayerColor player, const CGHeroInstance * hero, std::vector<std::string> words)
  415. {
  416. if (!hero)
  417. return;
  418. SetMovePoints smp;
  419. smp.hid = hero->id;
  420. bool unlimited = false;
  421. try
  422. {
  423. smp.val = std::stol(words.at(0));
  424. }
  425. catch(std::logic_error&)
  426. {
  427. smp.val = 1000000;
  428. unlimited = true;
  429. }
  430. gameHandler->sendAndApply(&smp);
  431. GiveBonus gb(GiveBonus::ETarget::OBJECT);
  432. gb.bonus.type = BonusType::FREE_SHIP_BOARDING;
  433. gb.bonus.duration = unlimited ? BonusDuration::PERMANENT : BonusDuration::ONE_DAY;
  434. gb.bonus.source = BonusSource::OTHER;
  435. gb.id = hero->id;
  436. gameHandler->giveHeroBonus(&gb);
  437. if(unlimited)
  438. {
  439. GiveBonus gb(GiveBonus::ETarget::OBJECT);
  440. gb.bonus.type = BonusType::UNLIMITED_MOVEMENT;
  441. gb.bonus.duration = BonusDuration::PERMANENT;
  442. gb.bonus.source = BonusSource::OTHER;
  443. gb.id = hero->id;
  444. gameHandler->giveHeroBonus(&gb);
  445. }
  446. }
  447. void PlayerMessageProcessor::cheatResources(PlayerColor player, std::vector<std::string> words)
  448. {
  449. int baseResourceAmount;
  450. try
  451. {
  452. baseResourceAmount = std::stol(words.at(0));
  453. }
  454. catch(std::logic_error&)
  455. {
  456. baseResourceAmount = 100;
  457. }
  458. TResources resources;
  459. resources[EGameResID::GOLD] = baseResourceAmount * 1000;
  460. for (GameResID i = EGameResID::WOOD; i < EGameResID::GOLD; ++i)
  461. resources[i] = baseResourceAmount;
  462. gameHandler->giveResources(player, resources);
  463. }
  464. void PlayerMessageProcessor::cheatVictory(PlayerColor player)
  465. {
  466. PlayerCheated pc;
  467. pc.player = player;
  468. pc.winningCheatCode = true;
  469. gameHandler->sendAndApply(&pc);
  470. }
  471. void PlayerMessageProcessor::cheatDefeat(PlayerColor player)
  472. {
  473. PlayerCheated pc;
  474. pc.player = player;
  475. pc.losingCheatCode = true;
  476. gameHandler->sendAndApply(&pc);
  477. }
  478. void PlayerMessageProcessor::cheatMapReveal(PlayerColor player, bool reveal)
  479. {
  480. FoWChange fc;
  481. fc.mode = reveal ? ETileVisibility::REVEALED : ETileVisibility::HIDDEN;
  482. fc.player = player;
  483. const auto & fowMap = gameHandler->gameState()->getPlayerTeam(player)->fogOfWarMap;
  484. const auto & mapSize = gameHandler->gameState()->getMapSize();
  485. auto hlp_tab = new int3[mapSize.x * mapSize.y * mapSize.z];
  486. int lastUnc = 0;
  487. for(int z = 0; z < mapSize.z; z++)
  488. for(int x = 0; x < mapSize.x; x++)
  489. for(int y = 0; y < mapSize.y; y++)
  490. if(!fowMap[z][x][y] || fc.mode == ETileVisibility::HIDDEN)
  491. hlp_tab[lastUnc++] = int3(x, y, z);
  492. fc.tiles.insert(hlp_tab, hlp_tab + lastUnc);
  493. delete [] hlp_tab;
  494. gameHandler->sendAndApply(&fc);
  495. }
  496. void PlayerMessageProcessor::cheatPuzzleReveal(PlayerColor player)
  497. {
  498. TeamState *t = gameHandler->gameState()->getPlayerTeam(player);
  499. for(auto & obj : gameHandler->gameState()->map->objects)
  500. {
  501. if(obj && obj->ID == Obj::OBELISK && !obj->wasVisited(player))
  502. {
  503. gameHandler->setObjPropertyID(obj->id, ObjProperty::OBELISK_VISITED, t->id);
  504. for(const auto & color : t->players)
  505. {
  506. gameHandler->setObjPropertyID(obj->id, ObjProperty::VISITED, color);
  507. PlayerCheated pc;
  508. pc.player = color;
  509. gameHandler->sendAndApply(&pc);
  510. }
  511. }
  512. }
  513. }
  514. void PlayerMessageProcessor::cheatMaxLuck(PlayerColor player, const CGHeroInstance * hero)
  515. {
  516. if (!hero)
  517. return;
  518. GiveBonus gb;
  519. gb.bonus = Bonus(BonusDuration::PERMANENT, BonusType::MAX_LUCK, BonusSource::OTHER, 0, BonusSourceID(Obj(Obj::NO_OBJ)));
  520. gb.id = hero->id;
  521. gameHandler->giveHeroBonus(&gb);
  522. }
  523. void PlayerMessageProcessor::cheatFly(PlayerColor player, const CGHeroInstance * hero)
  524. {
  525. if (!hero)
  526. return;
  527. GiveBonus gb;
  528. gb.bonus = Bonus(BonusDuration::PERMANENT, BonusType::FLYING_MOVEMENT, BonusSource::OTHER, 0, BonusSourceID(Obj(Obj::NO_OBJ)));
  529. gb.id = hero->id;
  530. gameHandler->giveHeroBonus(&gb);
  531. }
  532. void PlayerMessageProcessor::cheatMaxMorale(PlayerColor player, const CGHeroInstance * hero)
  533. {
  534. if (!hero)
  535. return;
  536. GiveBonus gb;
  537. gb.bonus = Bonus(BonusDuration::PERMANENT, BonusType::MAX_MORALE, BonusSource::OTHER, 0, BonusSourceID(Obj(Obj::NO_OBJ)));
  538. gb.id = hero->id;
  539. gameHandler->giveHeroBonus(&gb);
  540. }
  541. bool PlayerMessageProcessor::handleCheatCode(const std::string & cheat, PlayerColor player, ObjectInstanceID currObj)
  542. {
  543. std::vector<std::string> words;
  544. boost::split(words, boost::trim_copy(cheat), boost::is_any_of("\t\r\n "));
  545. if (words.empty() || !gameHandler->getStartInfo()->extraOptionsInfo.cheatsAllowed)
  546. return false;
  547. //Make cheat name case-insensitive, but keep words/parameters (e.g. creature name) as it
  548. std::string cheatName = boost::to_lower_copy(words[0]);
  549. words.erase(words.begin());
  550. std::vector<std::string> townTargetedCheats = { "vcmiarmenelos", "vcmibuild", "nwczion" };
  551. std::vector<std::string> playerTargetedCheats = {
  552. "vcmiformenos", "vcmiresources", "nwctheconstruct",
  553. "vcmimelkor", "vcmilose", "nwcbluepill",
  554. "vcmisilmaril", "vcmiwin", "nwcredpill",
  555. "vcmieagles", "vcmimap", "nwcwhatisthematrix",
  556. "vcmiungoliant", "vcmihidemap", "nwcignoranceisbliss",
  557. "vcmiobelisk", "nwcoracle"
  558. };
  559. std::vector<std::string> heroTargetedCheats = {
  560. "vcmiainur", "vcmiarchangel", "nwctrinity",
  561. "vcmiangband", "vcmiblackknight", "nwcagents",
  562. "vcmiglaurung", "vcmicrystal", "vcmiazure",
  563. "vcmifaerie", "vcmiarmy", "vcminissi",
  564. "vcmiistari", "vcmispells", "nwcthereisnospoon",
  565. "vcminoldor", "vcmimachines", "nwclotsofguns",
  566. "vcmiglorfindel", "vcmilevel", "nwcneo",
  567. "vcminahar", "vcmimove", "nwcnebuchadnezzar",
  568. "vcmiforgeofnoldorking", "vcmiartifacts",
  569. "vcmiolorin", "vcmiexp",
  570. "vcmiluck", "nwcfollowthewhiterabbit",
  571. "vcmimorale", "nwcmorpheus",
  572. "vcmigod", "nwctheone"
  573. };
  574. if (!vstd::contains(townTargetedCheats, cheatName) && !vstd::contains(playerTargetedCheats, cheatName) && !vstd::contains(heroTargetedCheats, cheatName))
  575. return false;
  576. bool playerTargetedCheat = false;
  577. for (const auto & i : gameHandler->gameState()->players)
  578. {
  579. if (words.empty())
  580. break;
  581. if (i.first == PlayerColor::NEUTRAL)
  582. continue;
  583. if (words.front() == "ai" && i.second.human)
  584. continue;
  585. if (words.front() != "all" && words.front() != i.first.toString())
  586. continue;
  587. std::vector<std::string> parameters = words;
  588. PlayerCheated pc;
  589. pc.player = i.first;
  590. gameHandler->sendAndApply(&pc);
  591. playerTargetedCheat = true;
  592. parameters.erase(parameters.begin());
  593. if (vstd::contains(playerTargetedCheats, cheatName))
  594. executeCheatCode(cheatName, i.first, ObjectInstanceID::NONE, parameters);
  595. if (vstd::contains(townTargetedCheats, cheatName))
  596. for (const auto & t : i.second.towns)
  597. executeCheatCode(cheatName, i.first, t->id, parameters);
  598. if (vstd::contains(heroTargetedCheats, cheatName))
  599. for (const auto & h : i.second.heroes)
  600. executeCheatCode(cheatName, i.first, h->id, parameters);
  601. }
  602. PlayerCheated pc;
  603. pc.player = player;
  604. gameHandler->sendAndApply(&pc);
  605. if (!playerTargetedCheat)
  606. executeCheatCode(cheatName, player, currObj, words);
  607. return true;
  608. }
  609. void PlayerMessageProcessor::executeCheatCode(const std::string & cheatName, PlayerColor player, ObjectInstanceID currObj, const std::vector<std::string> & words)
  610. {
  611. const CGHeroInstance * hero = gameHandler->getHero(currObj);
  612. const CGTownInstance * town = gameHandler->getTown(currObj);
  613. if (!town && hero)
  614. town = hero->visitedTown;
  615. const auto & doCheatGiveSpells = [&]() { cheatGiveSpells(player, hero); };
  616. const auto & doCheatBuildTown = [&]() { cheatBuildTown(player, town); };
  617. const auto & doCheatGiveArmyCustom = [&]() { cheatGiveArmy(player, hero, words); };
  618. const auto & doCheatGiveArmyFixed = [&](std::vector<std::string> customWords) { cheatGiveArmy(player, hero, customWords); };
  619. const auto & doCheatGiveMachines = [&]() { cheatGiveMachines(player, hero); };
  620. const auto & doCheatGiveArtifacts = [&]() { cheatGiveArtifacts(player, hero, words); };
  621. const auto & doCheatLevelup = [&]() { cheatLevelup(player, hero, words); };
  622. const auto & doCheatExperience = [&]() { cheatExperience(player, hero, words); };
  623. const auto & doCheatMovement = [&]() { cheatMovement(player, hero, words); };
  624. const auto & doCheatResources = [&]() { cheatResources(player, words); };
  625. const auto & doCheatVictory = [&]() { cheatVictory(player); };
  626. const auto & doCheatDefeat = [&]() { cheatDefeat(player); };
  627. const auto & doCheatMapReveal = [&]() { cheatMapReveal(player, true); };
  628. const auto & doCheatMapHide = [&]() { cheatMapReveal(player, false); };
  629. const auto & doCheatRevealPuzzle = [&]() { cheatPuzzleReveal(player); };
  630. const auto & doCheatMaxLuck = [&]() { cheatMaxLuck(player, hero); };
  631. const auto & doCheatMaxMorale = [&]() { cheatMaxMorale(player, hero); };
  632. const auto & doCheatTheOne = [&]()
  633. {
  634. if(!hero)
  635. return;
  636. cheatMapReveal(player, true);
  637. cheatGiveArmy(player, hero, { "archangel", "5" });
  638. cheatMovement(player, hero, { });
  639. cheatFly(player, hero);
  640. };
  641. // Unimplemented H3 cheats:
  642. // nwcphisherprice - Changes and brightens the game colors.
  643. std::map<std::string, std::function<void()>> callbacks = {
  644. {"vcmiainur", [&] () {doCheatGiveArmyFixed({ "archangel", "5" });} },
  645. {"nwctrinity", [&] () {doCheatGiveArmyFixed({ "archangel", "5" });} },
  646. {"vcmiangband", [&] () {doCheatGiveArmyFixed({ "blackKnight", "10" });} },
  647. {"vcmiglaurung", [&] () {doCheatGiveArmyFixed({ "crystalDragon", "5000" });} },
  648. {"vcmiarchangel", [&] () {doCheatGiveArmyFixed({ "archangel", "5" });} },
  649. {"nwcagents", [&] () {doCheatGiveArmyFixed({ "blackKnight", "10" });} },
  650. {"vcmiblackknight", [&] () {doCheatGiveArmyFixed({ "blackKnight", "10" });} },
  651. {"vcmicrystal", [&] () {doCheatGiveArmyFixed({ "crystalDragon", "5000" });} },
  652. {"vcmiazure", [&] () {doCheatGiveArmyFixed({ "azureDragon", "5000" });} },
  653. {"vcmifaerie", [&] () {doCheatGiveArmyFixed({ "fairieDragon", "5000" });} },
  654. {"vcmiarmy", doCheatGiveArmyCustom },
  655. {"vcminissi", doCheatGiveArmyCustom },
  656. {"vcmiistari", doCheatGiveSpells },
  657. {"vcmispells", doCheatGiveSpells },
  658. {"nwcthereisnospoon", doCheatGiveSpells },
  659. {"vcmiarmenelos", doCheatBuildTown },
  660. {"vcmibuild", doCheatBuildTown },
  661. {"nwczion", doCheatBuildTown },
  662. {"vcminoldor", doCheatGiveMachines },
  663. {"vcmimachines", doCheatGiveMachines },
  664. {"nwclotsofguns", doCheatGiveMachines },
  665. {"vcmiforgeofnoldorking", doCheatGiveArtifacts },
  666. {"vcmiartifacts", doCheatGiveArtifacts },
  667. {"vcmiglorfindel", doCheatLevelup },
  668. {"vcmilevel", doCheatLevelup },
  669. {"nwcneo", doCheatLevelup },
  670. {"vcmiolorin", doCheatExperience },
  671. {"vcmiexp", doCheatExperience },
  672. {"vcminahar", doCheatMovement },
  673. {"vcmimove", doCheatMovement },
  674. {"nwcnebuchadnezzar", doCheatMovement },
  675. {"vcmiformenos", doCheatResources },
  676. {"vcmiresources", doCheatResources },
  677. {"nwctheconstruct", doCheatResources },
  678. {"nwcbluepill", doCheatDefeat },
  679. {"vcmimelkor", doCheatDefeat },
  680. {"vcmilose", doCheatDefeat },
  681. {"nwcredpill", doCheatVictory },
  682. {"vcmisilmaril", doCheatVictory },
  683. {"vcmiwin", doCheatVictory },
  684. {"nwcwhatisthematrix", doCheatMapReveal },
  685. {"vcmieagles", doCheatMapReveal },
  686. {"vcmimap", doCheatMapReveal },
  687. {"vcmiungoliant", doCheatMapHide },
  688. {"vcmihidemap", doCheatMapHide },
  689. {"nwcignoranceisbliss", doCheatMapHide },
  690. {"vcmiobelisk", doCheatRevealPuzzle },
  691. {"nwcoracle", doCheatRevealPuzzle },
  692. {"vcmiluck", doCheatMaxLuck },
  693. {"nwcfollowthewhiterabbit", doCheatMaxLuck },
  694. {"vcmimorale", doCheatMaxMorale },
  695. {"nwcmorpheus", doCheatMaxMorale },
  696. {"vcmigod", doCheatTheOne },
  697. {"nwctheone", doCheatTheOne },
  698. };
  699. assert(callbacks.count(cheatName));
  700. if (callbacks.count(cheatName))
  701. callbacks.at(cheatName)();
  702. }
  703. void PlayerMessageProcessor::sendSystemMessage(std::shared_ptr<CConnection> connection, const MetaString & message)
  704. {
  705. SystemMessage sm;
  706. sm.text = message;
  707. connection->sendPack(&sm);
  708. }
  709. void PlayerMessageProcessor::sendSystemMessage(std::shared_ptr<CConnection> connection, const std::string & message)
  710. {
  711. MetaString str;
  712. str.appendRawString(message);
  713. sendSystemMessage(connection, str);
  714. }
  715. void PlayerMessageProcessor::broadcastSystemMessage(MetaString message)
  716. {
  717. SystemMessage sm;
  718. sm.text = message;
  719. gameHandler->sendToAllClients(&sm);
  720. }
  721. void PlayerMessageProcessor::broadcastSystemMessage(const std::string & message)
  722. {
  723. MetaString str;
  724. str.appendRawString(message);
  725. broadcastSystemMessage(str);
  726. }
  727. void PlayerMessageProcessor::broadcastMessage(PlayerColor playerSender, const std::string & message)
  728. {
  729. PlayerMessageClient temp_message(playerSender, message);
  730. gameHandler->sendAndApply(&temp_message);
  731. }