CHighScoreScreen.cpp 14 KB

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