CHighScoreScreen.cpp 14 KB

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