HighScoreState.cxx 2.3 KB

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