CHighScoreScreen.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. /*
  2. * CHighScoreScreen.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 "CHighScoreScreen.h"
  12. #include "../gui/CGuiHandler.h"
  13. #include "../gui/WindowHandler.h"
  14. #include "../gui/Shortcut.h"
  15. #include "../widgets/Buttons.h"
  16. #include "../widgets/CTextInput.h"
  17. #include "../widgets/Images.h"
  18. #include "../widgets/GraphicalPrimitiveCanvas.h"
  19. #include "../windows/InfoWindows.h"
  20. #include "../widgets/TextControls.h"
  21. #include "../render/Canvas.h"
  22. #include "../render/IRenderHandler.h"
  23. #include "../CGameInfo.h"
  24. #include "../CVideoHandler.h"
  25. #include "../CMusicHandler.h"
  26. #include "../../lib/CGeneralTextHandler.h"
  27. #include "../../lib/CConfigHandler.h"
  28. #include "../../lib/CCreatureHandler.h"
  29. #include "../../lib/constants/EntityIdentifiers.h"
  30. #include "../../lib/TextOperations.h"
  31. #include "../../lib/Languages.h"
  32. auto HighScoreCalculation::calculate()
  33. {
  34. struct Result
  35. {
  36. int basic = 0;
  37. int total = 0;
  38. int sumDays = 0;
  39. bool cheater = false;
  40. };
  41. Result firstResult;
  42. Result summary;
  43. const std::array<double, 5> difficultyMultipliers{0.8, 1.0, 1.3, 1.6, 2.0};
  44. for(auto & param : parameters)
  45. {
  46. double tmp = 200 - (param.day + 10) / (param.townAmount + 5) + (param.allDefeated ? 25 : 0) + (param.hasGrail ? 25 : 0);
  47. firstResult = Result{static_cast<int>(tmp), static_cast<int>(tmp * difficultyMultipliers.at(param.difficulty)), param.day, param.usedCheat};
  48. summary.basic += firstResult.basic * 5.0 / parameters.size();
  49. summary.total += firstResult.total * 5.0 / parameters.size();
  50. summary.sumDays += firstResult.sumDays;
  51. summary.cheater |= firstResult.cheater;
  52. }
  53. if(parameters.size() == 1)
  54. return firstResult;
  55. return summary;
  56. }
  57. CreatureID HighScoreCalculation::getCreatureForPoints(int points, bool campaign)
  58. {
  59. static const JsonNode configCreatures(JsonPath::builtin("CONFIG/highscoreCreatures.json"));
  60. auto creatures = configCreatures["creatures"].Vector();
  61. int divide = campaign ? 5 : 1;
  62. for(auto & creature : creatures)
  63. if(points / divide <= creature["max"].Integer() && points / divide >= creature["min"].Integer())
  64. return CreatureID::decode(creature["creature"].String());
  65. return -1;
  66. }
  67. CHighScoreScreen::CHighScoreScreen(HighScorePage highscorepage, int highlighted)
  68. : CWindowObject(BORDERED), highscorepage(highscorepage), highlighted(highlighted)
  69. {
  70. addUsedEvents(SHOW_POPUP);
  71. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  72. pos = center(Rect(0, 0, 800, 600));
  73. backgroundAroundMenu = std::make_shared<CFilledTexture>(ImagePath::builtin("DIBOXBCK"), Rect(-pos.x, -pos.y, GH.screenDimensions().x, GH.screenDimensions().y));
  74. addHighScores();
  75. addButtons();
  76. }
  77. void CHighScoreScreen::showPopupWindow(const Point & cursorPosition)
  78. {
  79. for (int i = 0; i < screenRows; i++)
  80. {
  81. bool currentGameNotInListEntry = i == (screenRows - 1) && highlighted > (screenRows - 1);
  82. Rect r = Rect(80, 40 + i * 50, 635, 50);
  83. if(r.isInside(cursorPosition - pos))
  84. {
  85. std::string tmp = persistentStorage["highscore"][highscorepage == HighScorePage::SCENARIO ? "scenario" : "campaign"][currentGameNotInListEntry ? highlighted : i]["datetime"].String();
  86. if(!tmp.empty())
  87. CRClickPopup::createAndPush(tmp);
  88. }
  89. }
  90. }
  91. void CHighScoreScreen::addButtons()
  92. {
  93. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  94. buttons.clear();
  95. buttons.push_back(std::make_shared<CButton>(Point(31, 113), AnimationPath::builtin("HISCCAM.DEF"), CButton::tooltip(), [&](){ buttonCampaignClick(); }));
  96. buttons.push_back(std::make_shared<CButton>(Point(31, 345), AnimationPath::builtin("HISCSTA.DEF"), CButton::tooltip(), [&](){ buttonScenarioClick(); }));
  97. buttons.push_back(std::make_shared<CButton>(Point(726, 113), AnimationPath::builtin("HISCRES.DEF"), CButton::tooltip(), [&](){ buttonResetClick(); }));
  98. buttons.push_back(std::make_shared<CButton>(Point(726, 345), AnimationPath::builtin("HISCEXT.DEF"), CButton::tooltip(), [&](){ buttonExitClick(); }));
  99. }
  100. void CHighScoreScreen::addHighScores()
  101. {
  102. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  103. background = std::make_shared<CPicture>(ImagePath::builtin(highscorepage == HighScorePage::SCENARIO ? "HISCORE" : "HISCORE2"));
  104. texts.clear();
  105. images.clear();
  106. // Header
  107. texts.push_back(std::make_shared<CLabel>(115, 20, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->translate("core.genrltxt.433"))); // rank
  108. texts.push_back(std::make_shared<CLabel>(225, 20, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->translate("core.genrltxt.434"))); // player
  109. if(highscorepage == HighScorePage::SCENARIO)
  110. {
  111. texts.push_back(std::make_shared<CLabel>(405, 20, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->translate("core.genrltxt.435"))); // land
  112. texts.push_back(std::make_shared<CLabel>(557, 20, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->translate("core.genrltxt.436"))); // days
  113. texts.push_back(std::make_shared<CLabel>(627, 20, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->translate("core.genrltxt.75"))); // score
  114. }
  115. else
  116. {
  117. texts.push_back(std::make_shared<CLabel>(405, 20, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->translate("core.genrltxt.672"))); // campaign
  118. texts.push_back(std::make_shared<CLabel>(592, 20, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->translate("core.genrltxt.75"))); // score
  119. }
  120. // Content
  121. int y = 66;
  122. auto & data = persistentStorage["highscore"][highscorepage == HighScorePage::SCENARIO ? "scenario" : "campaign"];
  123. for (int i = 0; i < screenRows; i++)
  124. {
  125. bool currentGameNotInListEntry = (i == (screenRows - 1) && highlighted > (screenRows - 1));
  126. auto & curData = data[currentGameNotInListEntry ? highlighted : i];
  127. ColorRGBA color = (i == highlighted || currentGameNotInListEntry) ? Colors::YELLOW : Colors::WHITE;
  128. texts.push_back(std::make_shared<CLabel>(115, y + i * 50, FONT_MEDIUM, ETextAlignment::CENTER, color, std::to_string((currentGameNotInListEntry ? highlighted : i) + 1)));
  129. std::string tmp = curData["player"].String();
  130. TextOperations::trimRightUnicode(tmp, std::max(0, (int)TextOperations::getUnicodeCharactersCount(tmp) - 13));
  131. texts.push_back(std::make_shared<CLabel>(225, y + i * 50, FONT_MEDIUM, ETextAlignment::CENTER, color, tmp));
  132. if(highscorepage == HighScorePage::SCENARIO)
  133. {
  134. std::string tmp = curData["scenarioName"].String();
  135. TextOperations::trimRightUnicode(tmp, std::max(0, (int)TextOperations::getUnicodeCharactersCount(tmp) - 25));
  136. texts.push_back(std::make_shared<CLabel>(405, y + i * 50, FONT_MEDIUM, ETextAlignment::CENTER, color, tmp));
  137. texts.push_back(std::make_shared<CLabel>(557, y + i * 50, FONT_MEDIUM, ETextAlignment::CENTER, color, std::to_string(curData["days"].Integer())));
  138. texts.push_back(std::make_shared<CLabel>(627, y + i * 50, FONT_MEDIUM, ETextAlignment::CENTER, color, std::to_string(curData["points"].Integer())));
  139. }
  140. else
  141. {
  142. std::string tmp = curData["campaignName"].String();
  143. TextOperations::trimRightUnicode(tmp, std::max(0, (int)TextOperations::getUnicodeCharactersCount(tmp) - 25));
  144. texts.push_back(std::make_shared<CLabel>(405, y + i * 50, FONT_MEDIUM, ETextAlignment::CENTER, color, tmp));
  145. texts.push_back(std::make_shared<CLabel>(592, y + i * 50, FONT_MEDIUM, ETextAlignment::CENTER, color, std::to_string(curData["points"].Integer())));
  146. }
  147. if(curData["points"].Integer() > 0 && curData["points"].Integer() <= ((highscorepage == HighScorePage::CAMPAIGN) ? 2500 : 500))
  148. images.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("CPRSMALL"), (*CGI->creh)[HighScoreCalculation::getCreatureForPoints(curData["points"].Integer(), highscorepage == HighScorePage::CAMPAIGN)]->getIconIndex(), 0, 670, y - 15 + i * 50));
  149. }
  150. }
  151. void CHighScoreScreen::buttonCampaignClick()
  152. {
  153. highscorepage = HighScorePage::CAMPAIGN;
  154. addHighScores();
  155. addButtons();
  156. redraw();
  157. }
  158. void CHighScoreScreen::buttonScenarioClick()
  159. {
  160. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  161. highscorepage = HighScorePage::SCENARIO;
  162. addHighScores();
  163. addButtons();
  164. redraw();
  165. }
  166. void CHighScoreScreen::buttonResetClick()
  167. {
  168. CInfoWindow::showYesNoDialog(
  169. CGI->generaltexth->allTexts[666],
  170. {},
  171. [this]()
  172. {
  173. Settings entry = persistentStorage.write["highscore"];
  174. entry->clear();
  175. addHighScores();
  176. addButtons();
  177. redraw();
  178. },
  179. 0
  180. );
  181. }
  182. void CHighScoreScreen::buttonExitClick()
  183. {
  184. close();
  185. }
  186. CHighScoreInputScreen::CHighScoreInputScreen(bool won, HighScoreCalculation calc)
  187. : CWindowObject(BORDERED), won(won), calc(calc), videoSoundHandle(-1)
  188. {
  189. addUsedEvents(LCLICK | KEYBOARD);
  190. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  191. pos = center(Rect(0, 0, 800, 600));
  192. backgroundAroundMenu = std::make_shared<CFilledTexture>(ImagePath::builtin("DIBOXBCK"), Rect(-pos.x, -pos.y, GH.screenDimensions().x, GH.screenDimensions().y));
  193. background = std::make_shared<TransparentFilledRectangle>(Rect(0, 0, pos.w, pos.h), Colors::BLACK);
  194. if(won)
  195. {
  196. int border = 100;
  197. int textareaW = ((pos.w - 2 * border) / 4);
  198. std::vector<std::string> t = { "438", "439", "440", "441", "676" }; // time, score, difficulty, final score, rank
  199. for (int i = 0; i < 5; i++)
  200. texts.push_back(std::make_shared<CMultiLineLabel>(Rect(textareaW * i + border - (textareaW / 2), 450, textareaW, 100), FONT_HIGH_SCORE, ETextAlignment::TOPCENTER, Colors::WHITE, CGI->generaltexth->translate("core.genrltxt." + t[i])));
  201. std::string creatureName = (calc.calculate().cheater) ? CGI->generaltexth->translate("core.genrltxt.260") : (*CGI->creh)[HighScoreCalculation::getCreatureForPoints(calc.calculate().total, calc.isCampaign)]->getNameSingularTranslated();
  202. t = { std::to_string(calc.calculate().sumDays), std::to_string(calc.calculate().basic), CGI->generaltexth->translate("core.arraytxt." + std::to_string((142 + calc.parameters[0].difficulty))), std::to_string(calc.calculate().total), creatureName };
  203. for (int i = 0; i < 5; i++)
  204. texts.push_back(std::make_shared<CMultiLineLabel>(Rect(textareaW * i + border - (textareaW / 2), 530, textareaW, 100), FONT_HIGH_SCORE, ETextAlignment::TOPCENTER, Colors::WHITE, t[i]));
  205. CCS->musich->playMusic(AudioPath::builtin("music/Win Scenario"), true, true);
  206. }
  207. else
  208. CCS->musich->playMusic(AudioPath::builtin("music/UltimateLose"), false, true);
  209. video = won ? "HSANIM.SMK" : "LOSEGAME.SMK";
  210. }
  211. int CHighScoreInputScreen::addEntry(std::string text) {
  212. std::vector<JsonNode> baseNode = persistentStorage["highscore"][calc.isCampaign ? "campaign" : "scenario"].Vector();
  213. auto sortFunctor = [](const JsonNode & left, const JsonNode & right)
  214. {
  215. if(left["points"].Integer() == right["points"].Integer())
  216. return left["posFlag"].Bool() > right["posFlag"].Bool();
  217. return left["points"].Integer() > right["points"].Integer();
  218. };
  219. JsonNode newNode = JsonNode();
  220. newNode["player"].String() = text;
  221. if(calc.isCampaign)
  222. newNode["campaignName"].String() = calc.calculate().cheater ? CGI->generaltexth->translate("core.genrltxt.260") : calc.parameters[0].campaignName;
  223. else
  224. newNode["scenarioName"].String() = calc.calculate().cheater ? CGI->generaltexth->translate("core.genrltxt.260") : calc.parameters[0].scenarioName;
  225. newNode["days"].Integer() = calc.calculate().sumDays;
  226. newNode["points"].Integer() = calc.calculate().cheater ? 0 : calc.calculate().total;
  227. newNode["datetime"].String() = TextOperations::getFormattedDateTimeLocal(std::time(nullptr));
  228. newNode["posFlag"].Bool() = true;
  229. baseNode.push_back(newNode);
  230. boost::range::sort(baseNode, sortFunctor);
  231. int pos = -1;
  232. for (int i = 0; i < baseNode.size(); i++)
  233. {
  234. if(!baseNode[i]["posFlag"].isNull())
  235. {
  236. baseNode[i]["posFlag"].clear();
  237. pos = i;
  238. }
  239. }
  240. Settings s = persistentStorage.write["highscore"][calc.isCampaign ? "campaign" : "scenario"];
  241. s->Vector() = baseNode;
  242. return pos;
  243. }
  244. void CHighScoreInputScreen::show(Canvas & to)
  245. {
  246. if(background)
  247. background->show(to);
  248. CCS->videoh->update(pos.x, pos.y, to.getInternalSurface(), true, false,
  249. [&]()
  250. {
  251. if(won)
  252. {
  253. CCS->videoh->close();
  254. video = "HSLOOP.SMK";
  255. auto audioData = CCS->videoh->getAudio(VideoPath::builtin(video));
  256. videoSoundHandle = CCS->soundh->playSound(audioData);
  257. CCS->videoh->open(VideoPath::builtin(video));
  258. }
  259. else
  260. close();
  261. });
  262. if(input)
  263. input->showAll(to);
  264. for(auto & text : texts)
  265. text->showAll(to);
  266. CIntObject::show(to);
  267. }
  268. void CHighScoreInputScreen::activate()
  269. {
  270. auto audioData = CCS->videoh->getAudio(VideoPath::builtin(video));
  271. videoSoundHandle = CCS->soundh->playSound(audioData);
  272. if(!CCS->videoh->open(VideoPath::builtin(video)))
  273. {
  274. if(!won)
  275. close();
  276. }
  277. else
  278. background = nullptr;
  279. CIntObject::activate();
  280. }
  281. void CHighScoreInputScreen::deactivate()
  282. {
  283. CCS->videoh->close();
  284. CCS->soundh->stopSound(videoSoundHandle);
  285. }
  286. void CHighScoreInputScreen::clickPressed(const Point & cursorPosition)
  287. {
  288. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  289. if(!won)
  290. {
  291. close();
  292. return;
  293. }
  294. if(!input)
  295. {
  296. input = std::make_shared<CHighScoreInput>(calc.parameters[0].playerName,
  297. [&] (std::string text)
  298. {
  299. if(!text.empty())
  300. {
  301. int pos = addEntry(text);
  302. close();
  303. GH.windows().createAndPushWindow<CHighScoreScreen>(calc.isCampaign ? CHighScoreScreen::HighScorePage::CAMPAIGN : CHighScoreScreen::HighScorePage::SCENARIO, pos);
  304. }
  305. else
  306. close();
  307. });
  308. }
  309. }
  310. void CHighScoreInputScreen::keyPressed(EShortcut key)
  311. {
  312. clickPressed(Point());
  313. }
  314. CHighScoreInput::CHighScoreInput(std::string playerName, std::function<void(std::string text)> readyCB)
  315. : CWindowObject(NEEDS_ANIMATED_BACKGROUND, ImagePath::builtin("HIGHNAME")), ready(readyCB)
  316. {
  317. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  318. pos = center(Rect(0, 0, 232, 212));
  319. updateShadow();
  320. text = std::make_shared<CMultiLineLabel>(Rect(15, 15, 202, 202), FONT_SMALL, ETextAlignment::TOPCENTER, Colors::WHITE, CGI->generaltexth->translate("core.genrltxt.96"));
  321. buttonOk = std::make_shared<CButton>(Point(26, 142), AnimationPath::builtin("MUBCHCK.DEF"), CGI->generaltexth->zelp[560], std::bind(&CHighScoreInput::okay, this), EShortcut::GLOBAL_ACCEPT);
  322. buttonCancel = std::make_shared<CButton>(Point(142, 142), AnimationPath::builtin("MUBCANC.DEF"), CGI->generaltexth->zelp[561], std::bind(&CHighScoreInput::abort, this), EShortcut::GLOBAL_CANCEL);
  323. statusBar = CGStatusBar::create(std::make_shared<CPicture>(background->getSurface(), Rect(7, 186, 218, 18), 7, 186));
  324. textInput = std::make_shared<CTextInput>(Rect(18, 104, 200, 25), FONT_SMALL, ETextAlignment::CENTER, true);
  325. textInput->setText(playerName);
  326. }
  327. void CHighScoreInput::okay()
  328. {
  329. ready(textInput->getText());
  330. }
  331. void CHighScoreInput::abort()
  332. {
  333. ready("");
  334. }