HighScoreState.cxx 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #include "HighScoreState.hxx"
  2. #include "HighScoreManager.hxx"
  3. #include "GameStateManager.hxx"
  4. #include "TranslationManager.hxx"
  5. #include "../SDLRenderer.hxx"
  6. HighScoreState::HighScoreState()
  7. :font_{"kenney_pixel.ttf"}
  8. {
  9. }
  10. void HighScoreState::on_event(GameStateManager& gsm, SDL_Event const& event)
  11. {
  12. if (event.type==SDL_KEYUP) {
  13. switch (event.key.keysym.scancode) {
  14. default:
  15. break;
  16. case SDL_SCANCODE_ESCAPE:
  17. [[fallthrough]];
  18. case SDL_SCANCODE_RETURN:
  19. gsm.pop_state();
  20. break;
  21. }
  22. }
  23. }
  24. void HighScoreState::render(SDLRenderer& renderer)
  25. {
  26. TTF_Font* const font = font_;
  27. SDL_Rect viewport;
  28. SDL_RenderGetViewport(renderer, &viewport);
  29. int width = viewport.w;
  30. SDL_SetRenderDrawColor(renderer, 0, 0, 0, SDL_ALPHA_OPAQUE);
  31. SDL_RenderClear(renderer);
  32. SDL_Color const color = {255, 255, 255, SDL_ALPHA_OPAQUE};
  33. int current_height = 80;
  34. render_heading(renderer, width, color, current_height);
  35. auto const scores = HighScoreManager::instance().get_scores();
  36. for (auto const& score: scores) {
  37. std::string text = score.player_name_+": "+std::to_string(score.points_);
  38. SDL_Surface* surface = TTF_RenderUTF8_Solid(font, text.c_str(), color);
  39. SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, surface);
  40. SDL_Rect textRect;
  41. textRect.w = surface->w;
  42. textRect.h = surface->h;
  43. textRect.x = (width-textRect.w)/2;
  44. textRect.y = current_height;
  45. SDL_RenderCopy(renderer, texture, nullptr, &textRect);
  46. SDL_FreeSurface(surface);
  47. SDL_DestroyTexture(texture);
  48. current_height += textRect.h;
  49. }
  50. SDL_RenderPresent(renderer);
  51. }
  52. void HighScoreState::render_heading(SDLRenderer& renderer, int const width, SDL_Color const& color, int& current_height)
  53. {
  54. SDL_Surface* headingSurface = TTF_RenderUTF8_Solid(font_,
  55. TranslationManager::instance().get_translation("High Scores").c_str(), color);
  56. SDL_Texture* headingTexture = SDL_CreateTextureFromSurface(renderer, headingSurface);
  57. SDL_Rect heading_rect;
  58. heading_rect.w = headingSurface->w*2;
  59. heading_rect.h = headingSurface->h*2;
  60. heading_rect.x = (width-heading_rect.w)/2;
  61. heading_rect.y = current_height;
  62. SDL_RenderCopy(renderer, headingTexture, nullptr, &heading_rect);
  63. SDL_FreeSurface(headingSurface);
  64. SDL_DestroyTexture(headingTexture);
  65. current_height += heading_rect.h;
  66. }