HighScoreState.cxx 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. render_heading(renderer, width, color);
  34. auto const scores = HighScoreManager::instance().get_scores();
  35. for (auto n = scores.size(); n--;) {
  36. auto const current_height = 180+static_cast<int>(n)*50;
  37. auto const& score = scores[n];
  38. std::string const text = std::to_string(n+1)+" - "+score.player_name_+": "+std::to_string(score.points_);
  39. SDL_Surface* surface = TTF_RenderUTF8_Solid(font, text.c_str(), color);
  40. SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, surface);
  41. SDL_Rect textRect;
  42. textRect.w = surface->w;
  43. textRect.h = surface->h;
  44. textRect.x = (width-textRect.w)/2;
  45. textRect.y = current_height;
  46. SDL_RenderCopy(renderer, texture, nullptr, &textRect);
  47. SDL_FreeSurface(surface);
  48. SDL_DestroyTexture(texture);
  49. }
  50. SDL_RenderPresent(renderer);
  51. }
  52. void HighScoreState::render_heading(SDLRenderer& renderer, int const width, SDL_Color const& color)
  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 = 80;
  62. SDL_RenderCopy(renderer, headingTexture, nullptr, &heading_rect);
  63. SDL_FreeSurface(headingSurface);
  64. SDL_DestroyTexture(headingTexture);
  65. }