CHighScoreScreen.cpp 14 KB

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