CHighScoreScreen.cpp 14 KB

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