CHighScoreScreen.cpp 14 KB

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