PlayingState.hxx 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #pragma once
  2. #ifndef SNAKE_PLAYINGSTATE_HXX
  3. #define SNAKE_PLAYINGSTATE_HXX
  4. #include "GameState.hxx"
  5. #include "AssetManager.hxx"
  6. #include <deque>
  7. #include <optional>
  8. #include <random>
  9. enum class Direction {
  10. Up,
  11. Right,
  12. Down,
  13. Left,
  14. };
  15. class PlayingState final : public GameState {
  16. public:
  17. static int constexpr CELLS_X = 64;
  18. static int constexpr CELLS_Y = 48;
  19. static float constexpr ACCELERATION = 1.05f;
  20. static float constexpr MAX_DISTANCE = 1.0f; // one cell per cycle
  21. static float constexpr START_SPEED = 0.005f; // 5 cell per second
  22. static float constexpr MAX_SPEED = 0.01f; // 20 cells per second
  23. PlayingState();
  24. void on_enter(GameStateManager& gsm) override;
  25. void on_event(GameStateManager& gsm, SDL_Event const& evt) override;
  26. void update(GameStateManager& gsm, std::chrono::milliseconds delta_time) override;
  27. void render(SDLRenderer& renderer) override;
  28. void render_game(SDLRenderer& renderer, bool is_current_state = true);
  29. private:
  30. void place_head();
  31. bool place_target();
  32. void render_ui(SDLRenderer& renderer, SDL_Rect const& playing_field);
  33. void render_target(SDLRenderer& renderer, SDL_Rect const& playing_field);
  34. void render_snake(SDLRenderer& renderer, SDL_Rect const& playing_field);
  35. bool detect_death(SDL_Point const& position);
  36. void handle_direction_change();
  37. std::mt19937 generator_;
  38. std::uniform_int_distribution<int> distribution_position_x_{0, CELLS_X-1};
  39. std::uniform_int_distribution<int> distribution_position_y_{0, CELLS_Y-1};
  40. SDL_Point target_{};
  41. unsigned length_{0u};
  42. Direction direction_{Direction::Left};
  43. std::optional<Direction> new_direction_{};
  44. SDL_FPoint head_{};
  45. std::deque<SDL_Point> tail_;
  46. float speed_{0.001f};
  47. int fps_{0};
  48. Asset<TTF_Font*> font_;
  49. };
  50. #endif // SNAKE_PLAYINGSTATE_HXX