PlayerMessageProcessor.cpp 27 KB

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