CHighScoreScreen.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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 "CStatisticScreen.h"
  13. #include "CMainMenu.h"
  14. #include "../GameEngine.h"
  15. #include "../GameInstance.h"
  16. #include "../gui/WindowHandler.h"
  17. #include "../gui/Shortcut.h"
  18. #include "../media/IMusicPlayer.h"
  19. #include "../media/ISoundPlayer.h"
  20. #include "../widgets/Buttons.h"
  21. #include "../widgets/CTextInput.h"
  22. #include "../widgets/Images.h"
  23. #include "../widgets/GraphicalPrimitiveCanvas.h"
  24. #include "../widgets/VideoWidget.h"
  25. #include "../windows/InfoWindows.h"
  26. #include "../widgets/TextControls.h"
  27. #include "../render/Canvas.h"
  28. #include "../render/IRenderHandler.h"
  29. #include "../../lib/texts/CGeneralTextHandler.h"
  30. #include "../../lib/texts/TextOperations.h"
  31. #include "../../lib/CConfigHandler.h"
  32. #include "../../lib/CCreatureHandler.h"
  33. #include "../../lib/constants/EntityIdentifiers.h"
  34. #include "../../lib/gameState/HighScore.h"
  35. #include "../../lib/gameState/GameStatistics.h"
  36. #include "../../lib/GameLibrary.h"
  37. #include "../../lib/serializer/JsonSerializer.h"
  38. #include "../../lib/serializer/JsonDeserializer.h"
  39. CHighScoreScreen::CHighScoreScreen(HighScorePage highscorepage, int highlighted)
  40. : CWindowObject(BORDERED), highscorepage(highscorepage), highlighted(highlighted)
  41. {
  42. addUsedEvents(LCLICK);
  43. addUsedEvents(SHOW_POPUP);
  44. OBJECT_CONSTRUCTION;
  45. pos = center(Rect(0, 0, 800, 600));
  46. addHighScores();
  47. addButtons();
  48. }
  49. void CHighScoreScreen::rowEvent(std::function<void(int row, bool currentGameNotInListEntry)> func, const Point & cursorPosition)
  50. {
  51. for (int i = 0; i < screenRows; i++)
  52. {
  53. bool currentGameNotInListEntry = i == (screenRows - 1) && highlighted > (screenRows - 1);
  54. Rect r = Rect(80, 40 + i * 50, 635, 50);
  55. if(r.isInside(cursorPosition - pos))
  56. func(i, currentGameNotInListEntry);
  57. }
  58. }
  59. void CHighScoreScreen::clickPressed(const Point & cursorPosition)
  60. {
  61. rowEvent([this](int row, bool currentGameNotInListEntry){
  62. auto node = persistentStorage["highscore"][highscorepage == HighScorePage::SCENARIO ? "scenario" : "campaign"][currentGameNotInListEntry ? highlighted : row];
  63. if(node["statistic"].isNull())
  64. return;
  65. JsonDeserializer ser(nullptr, node);
  66. StatisticDataSet stat;
  67. ser.serializeStruct("statistic", stat);
  68. ENGINE->windows().createAndPushWindow<CStatisticScreen>(stat);
  69. }, cursorPosition);
  70. }
  71. void CHighScoreScreen::showPopupWindow(const Point & cursorPosition)
  72. {
  73. rowEvent([this](int row, bool currentGameNotInListEntry){
  74. std::string tmp = persistentStorage["highscore"][highscorepage == HighScorePage::SCENARIO ? "scenario" : "campaign"][currentGameNotInListEntry ? highlighted : row]["datetime"].String();
  75. if(!tmp.empty())
  76. CRClickPopup::createAndPush("{" + LIBRARY->generaltexth->translate("core.help.316.hover") + "}\n\n" + tmp);
  77. }, cursorPosition);
  78. }
  79. void CHighScoreScreen::addButtons()
  80. {
  81. OBJECT_CONSTRUCTION;
  82. buttons.clear();
  83. buttons.push_back(std::make_shared<CButton>(Point(31, 113), AnimationPath::builtin("HISCCAM.DEF"), CButton::tooltip(), [this](){ buttonCampaignClick(); }, EShortcut::HIGH_SCORES_CAMPAIGNS));
  84. buttons.push_back(std::make_shared<CButton>(Point(31, 345), AnimationPath::builtin("HISCSTA.DEF"), CButton::tooltip(), [this](){ buttonScenarioClick(); }, EShortcut::HIGH_SCORES_SCENARIOS));
  85. buttons.push_back(std::make_shared<CButton>(Point(726, 113), AnimationPath::builtin("HISCRES.DEF"), CButton::tooltip(), [this](){ buttonResetClick(); }, EShortcut::HIGH_SCORES_RESET));
  86. buttons.push_back(std::make_shared<CButton>(Point(726, 345), AnimationPath::builtin("HISCEXT.DEF"), CButton::tooltip(), [this](){ buttonExitClick(); }, EShortcut::GLOBAL_RETURN));
  87. }
  88. void CHighScoreScreen::addHighScores()
  89. {
  90. OBJECT_CONSTRUCTION;
  91. background = std::make_shared<CPicture>(ImagePath::builtin(highscorepage == HighScorePage::SCENARIO ? "HISCORE" : "HISCORE2"));
  92. texts.clear();
  93. images.clear();
  94. // Header
  95. texts.push_back(std::make_shared<CLabel>(115, 20, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, LIBRARY->generaltexth->translate("core.genrltxt.433"))); // rank
  96. texts.push_back(std::make_shared<CLabel>(225, 20, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, LIBRARY->generaltexth->translate("core.genrltxt.434"))); // player
  97. if(highscorepage == HighScorePage::SCENARIO)
  98. {
  99. texts.push_back(std::make_shared<CLabel>(405, 20, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, LIBRARY->generaltexth->translate("core.genrltxt.435"))); // land
  100. texts.push_back(std::make_shared<CLabel>(557, 20, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, LIBRARY->generaltexth->translate("core.genrltxt.436"))); // days
  101. texts.push_back(std::make_shared<CLabel>(627, 20, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, LIBRARY->generaltexth->translate("core.genrltxt.75"))); // score
  102. }
  103. else
  104. {
  105. texts.push_back(std::make_shared<CLabel>(405, 20, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, LIBRARY->generaltexth->translate("core.genrltxt.672"))); // campaign
  106. texts.push_back(std::make_shared<CLabel>(592, 20, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, LIBRARY->generaltexth->translate("core.genrltxt.75"))); // score
  107. }
  108. // Content
  109. int y = 66;
  110. auto & data = persistentStorage["highscore"][highscorepage == HighScorePage::SCENARIO ? "scenario" : "campaign"];
  111. for (int i = 0; i < screenRows; i++)
  112. {
  113. bool currentGameNotInListEntry = (i == (screenRows - 1) && highlighted > (screenRows - 1));
  114. auto & curData = data[currentGameNotInListEntry ? highlighted : i];
  115. ColorRGBA color = (i == highlighted || currentGameNotInListEntry) ? Colors::YELLOW : Colors::WHITE;
  116. texts.push_back(std::make_shared<CLabel>(115, y + i * 50, FONT_MEDIUM, ETextAlignment::CENTER, color, std::to_string((currentGameNotInListEntry ? highlighted : i) + 1)));
  117. texts.push_back(std::make_shared<CLabel>(225, y + i * 50, FONT_MEDIUM, ETextAlignment::CENTER, color, curData["player"].String(), 120));
  118. if(highscorepage == HighScorePage::SCENARIO)
  119. {
  120. texts.push_back(std::make_shared<CLabel>(405, y + i * 50, FONT_MEDIUM, ETextAlignment::CENTER, color, curData["scenarioName"].String(), 200));
  121. texts.push_back(std::make_shared<CLabel>(557, y + i * 50, FONT_MEDIUM, ETextAlignment::CENTER, color, std::to_string(curData["days"].Integer())));
  122. texts.push_back(std::make_shared<CLabel>(627, y + i * 50, FONT_MEDIUM, ETextAlignment::CENTER, color, std::to_string(curData["points"].Integer())));
  123. }
  124. else
  125. {
  126. texts.push_back(std::make_shared<CLabel>(405, y + i * 50, FONT_MEDIUM, ETextAlignment::CENTER, color, curData["campaignName"].String(), 200));
  127. texts.push_back(std::make_shared<CLabel>(592, y + i * 50, FONT_MEDIUM, ETextAlignment::CENTER, color, std::to_string(curData["points"].Integer())));
  128. }
  129. if(curData["points"].Integer() > 0 && curData["points"].Integer() <= ((highscorepage == HighScorePage::CAMPAIGN) ? 2500 : 500))
  130. images.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("CPRSMALL"), (*LIBRARY->creh)[HighScoreCalculation::getCreatureForPoints(curData["points"].Integer(), highscorepage == HighScorePage::CAMPAIGN)]->getIconIndex(), 0, 670, y - 15 + i * 50));
  131. }
  132. }
  133. void CHighScoreScreen::buttonCampaignClick()
  134. {
  135. highscorepage = HighScorePage::CAMPAIGN;
  136. addHighScores();
  137. addButtons();
  138. redraw();
  139. }
  140. void CHighScoreScreen::buttonScenarioClick()
  141. {
  142. OBJECT_CONSTRUCTION;
  143. highscorepage = HighScorePage::SCENARIO;
  144. addHighScores();
  145. addButtons();
  146. redraw();
  147. }
  148. void CHighScoreScreen::buttonResetClick()
  149. {
  150. CInfoWindow::showYesNoDialog(
  151. LIBRARY->generaltexth->allTexts[666],
  152. {},
  153. [this]()
  154. {
  155. Settings entry = persistentStorage.write["highscore"];
  156. entry->clear();
  157. addHighScores();
  158. addButtons();
  159. redraw();
  160. },
  161. 0
  162. );
  163. }
  164. void CHighScoreScreen::buttonExitClick()
  165. {
  166. close();
  167. GAME->mainmenu()->playMusic();
  168. }
  169. void CHighScoreScreen::showAll(Canvas & to)
  170. {
  171. to.fillTexture(ENGINE->renderHandler().loadImage(ImagePath::builtin("DiBoxBck"), EImageBlitMode::OPAQUE));
  172. CWindowObject::showAll(to);
  173. }
  174. CHighScoreInputScreen::CHighScoreInputScreen(bool won, HighScoreCalculation calc, const StatisticDataSet & statistic)
  175. : CWindowObject(BORDERED), won(won), calc(calc), stat(statistic)
  176. {
  177. addUsedEvents(LCLICK | KEYBOARD);
  178. OBJECT_CONSTRUCTION;
  179. pos = center(Rect(0, 0, 800, 600));
  180. background = std::make_shared<TransparentFilledRectangle>(Rect(0, 0, pos.w, pos.h), Colors::BLACK);
  181. if(won)
  182. {
  183. videoPlayer = std::make_shared<VideoWidget>(Point(0, 0), VideoPath::builtin("HSANIM.SMK"), VideoPath::builtin("HSLOOP.SMK"), true);
  184. int border = 100;
  185. int textareaW = ((pos.w - 2 * border) / 4);
  186. std::vector<std::string> t = { "438", "439", "440", "441", "676" }; // time, score, difficulty, final score, rank
  187. for (int i = 0; i < 5; i++)
  188. texts.push_back(std::make_shared<CMultiLineLabel>(Rect(textareaW * i + border - (textareaW / 2), 450, textareaW, 100), FONT_HIGH_SCORE, ETextAlignment::TOPCENTER, Colors::WHITE, LIBRARY->generaltexth->translate("core.genrltxt." + t[i])));
  189. std::string creatureName = (calc.calculate().cheater) ? LIBRARY->generaltexth->translate("core.genrltxt.260") : (*LIBRARY->creh)[HighScoreCalculation::getCreatureForPoints(calc.calculate().total, calc.isCampaign)]->getNameSingularTranslated();
  190. t = { std::to_string(calc.calculate().sumDays), std::to_string(calc.calculate().basic), LIBRARY->generaltexth->translate("core.arraytxt." + std::to_string((142 + calc.parameters[0].difficulty))), std::to_string(calc.calculate().total), creatureName };
  191. for (int i = 0; i < 5; i++)
  192. 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]));
  193. ENGINE->music().playMusic(AudioPath::builtin("music/Win Scenario"), true, true);
  194. }
  195. else
  196. {
  197. videoPlayer = std::make_shared<VideoWidgetOnce>(Point(0, 0), VideoPath::builtin("LOSEGAME.SMK"), true, this);
  198. ENGINE->music().playMusic(AudioPath::builtin("music/UltimateLose"), false, true);
  199. }
  200. if (settings["general"]["enableUiEnhancements"].Bool())
  201. {
  202. statisticButton = std::make_shared<CButton>(Point(726, 10), AnimationPath::builtin("TPTAV02.DEF"), CButton::tooltip(LIBRARY->generaltexth->translate("vcmi.statisticWindow.statistics")), [this](){ ENGINE->windows().createAndPushWindow<CStatisticScreen>(stat); }, EShortcut::HIGH_SCORES_STATISTICS);
  203. texts.push_back(std::make_shared<CLabel>(716, 25, EFonts::FONT_HIGH_SCORE, ETextAlignment::CENTERRIGHT, Colors::WHITE, LIBRARY->generaltexth->translate("vcmi.statisticWindow.statistics") + ":"));
  204. }
  205. }
  206. void CHighScoreInputScreen::stopMusicAndClose()
  207. {
  208. GAME->mainmenu()->playMusic();
  209. close();
  210. }
  211. void CHighScoreInputScreen::onVideoPlaybackFinished()
  212. {
  213. stopMusicAndClose();
  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 ? LIBRARY->generaltexth->translate("core.genrltxt.260") : calc.parameters[0].campaignName;
  227. else
  228. newNode["scenarioName"].String() = calc.calculate().cheater ? LIBRARY->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. if(!calc.isCampaign)
  234. {
  235. JsonSerializer ser(nullptr, newNode);
  236. ser.serializeStruct("statistic", stat);
  237. }
  238. int highscoreEntriesCap = settings["general"]["highscoreEntriesCap"].Integer();
  239. if (baseNode.size() > highscoreEntriesCap - 1)
  240. baseNode.resize(highscoreEntriesCap - 1);
  241. baseNode.push_back(newNode);
  242. boost::range::sort(baseNode, sortFunctor);
  243. int pos = -1;
  244. for (int i = 0; i < baseNode.size(); i++)
  245. {
  246. if(!baseNode[i]["statistic"].isNull() && i >= settings["general"]["highscoreStatisticEntriesCap"].Integer() && baseNode[i]["posFlag"].isNull())
  247. baseNode[i]["statistic"].clear();
  248. if(!baseNode[i]["posFlag"].isNull())
  249. {
  250. baseNode[i]["posFlag"].clear();
  251. pos = i;
  252. }
  253. }
  254. Settings s = persistentStorage.write["highscore"][calc.isCampaign ? "campaign" : "scenario"];
  255. s->Vector() = baseNode;
  256. return pos;
  257. }
  258. void CHighScoreInputScreen::show(Canvas & to)
  259. {
  260. CWindowObject::showAll(to);
  261. }
  262. void CHighScoreInputScreen::showAll(Canvas & to)
  263. {
  264. to.fillTexture(ENGINE->renderHandler().loadImage(ImagePath::builtin("DiBoxBck"), EImageBlitMode::OPAQUE));
  265. CWindowObject::showAll(to);
  266. }
  267. void CHighScoreInputScreen::clickPressed(const Point & cursorPosition)
  268. {
  269. if(statisticButton && statisticButton->pos.isInside(cursorPosition))
  270. return;
  271. OBJECT_CONSTRUCTION;
  272. if(!won)
  273. {
  274. stopMusicAndClose();
  275. return;
  276. }
  277. if(!input)
  278. {
  279. input = std::make_shared<CHighScoreInput>(calc.parameters[0].playerName,
  280. [&] (std::string text)
  281. {
  282. if(!text.empty())
  283. {
  284. int pos = addEntry(text);
  285. close();
  286. ENGINE->windows().createAndPushWindow<CHighScoreScreen>(calc.isCampaign ? CHighScoreScreen::HighScorePage::CAMPAIGN : CHighScoreScreen::HighScorePage::SCENARIO, pos);
  287. }
  288. else
  289. stopMusicAndClose();
  290. });
  291. }
  292. }
  293. void CHighScoreInputScreen::keyPressed(EShortcut key)
  294. {
  295. if(key == EShortcut::HIGH_SCORES_STATISTICS) // ignore shortcut for skipping video with key
  296. return;
  297. clickPressed(Point());
  298. }
  299. CHighScoreInput::CHighScoreInput(std::string playerName, std::function<void(std::string text)> readyCB)
  300. : CWindowObject(NEEDS_ANIMATED_BACKGROUND, ImagePath::builtin("HIGHNAME")), ready(readyCB)
  301. {
  302. OBJECT_CONSTRUCTION;
  303. pos = center(Rect(0, 0, 232, 212));
  304. updateShadow();
  305. text = std::make_shared<CMultiLineLabel>(Rect(15, 15, 202, 202), FONT_SMALL, ETextAlignment::TOPCENTER, Colors::WHITE, LIBRARY->generaltexth->translate("core.genrltxt.96"));
  306. buttonOk = std::make_shared<CButton>(Point(26, 142), AnimationPath::builtin("MUBCHCK.DEF"), LIBRARY->generaltexth->zelp[560], std::bind(&CHighScoreInput::okay, this), EShortcut::GLOBAL_ACCEPT);
  307. buttonCancel = std::make_shared<CButton>(Point(142, 142), AnimationPath::builtin("MUBCANC.DEF"), LIBRARY->generaltexth->zelp[561], std::bind(&CHighScoreInput::abort, this), EShortcut::GLOBAL_CANCEL);
  308. // FIXME: broken. Never activates?
  309. // statusBar = CGStatusBar::create(std::make_shared<CPicture>(background->getSurface(), Rect(7, 186, 218, 18), 7, 186));
  310. textInput = std::make_shared<CTextInput>(Rect(18, 104, 200, 25), FONT_SMALL, ETextAlignment::CENTER, true);
  311. textInput->setText(playerName);
  312. }
  313. void CHighScoreInput::okay()
  314. {
  315. ready(textInput->getText());
  316. }
  317. void CHighScoreInput::abort()
  318. {
  319. ready("");
  320. }