PlayerMessageProcessor.cpp 27 KB

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