PlayingState.cxx 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. #include "PlayingState.hxx"
  2. #include "GameStateManager.hxx"
  3. #include <algorithm>
  4. #include <cfenv>
  5. #include <cmath>
  6. #include <format>
  7. #include <random>
  8. namespace {
  9. SDL_Point head_position(SDL_FPoint const& position)
  10. {
  11. #pragma STDC FENV_ACCESS ON
  12. std::fesetround(FE_TONEAREST);
  13. return {
  14. .x = static_cast<int>(std::nearbyint(position.x)),
  15. .y = static_cast<int>(std::nearbyint(position.y)),
  16. };
  17. }
  18. }
  19. static bool operator==(SDL_Point const& lhs, SDL_Point const& rhs)
  20. {
  21. return lhs.x==rhs.x && lhs.y==rhs.y;
  22. }
  23. static bool operator!=(SDL_Point const& lhs, SDL_Point const& rhs)
  24. {
  25. return lhs.x!=rhs.x || lhs.y!=rhs.y;
  26. }
  27. PlayingState::PlayingState()
  28. :generator_{std::random_device{}()}, font_{"kenney_pixel.ttf"}
  29. {
  30. }
  31. void PlayingState::on_enter(GameStateManager& gsm)
  32. {
  33. (void) gsm;
  34. length_ = 10u;
  35. std::uniform_int_distribution<int> distribution_direction{0, 3};
  36. direction_ = static_cast<Direction>(distribution_direction(generator_));
  37. place_head();
  38. place_target();
  39. tail_.clear();
  40. speed_ = START_SPEED;
  41. }
  42. void PlayingState::on_event(GameStateManager& gsm, SDL_Event const& evt)
  43. {
  44. if (evt.type==SDL_KEYUP) {
  45. auto const scancode = evt.key.keysym.scancode;
  46. if (scancode==SDL_SCANCODE_ESCAPE || scancode==SDL_SCANCODE_PAUSE)
  47. gsm.push_state(GameStates::MainMenu);
  48. }
  49. }
  50. void PlayingState::update(GameStateManager& gsm, std::chrono::milliseconds const delta_time)
  51. {
  52. handle_direction_change();
  53. auto const distance = speed_*static_cast<float>(delta_time.count());
  54. if (distance>MAX_DISTANCE) {
  55. SDL_Log("Snake would move a distance of %f. Game might have been stuck. Skipping cycle.", distance);
  56. return;
  57. }
  58. auto const direction = new_direction_.value_or(direction_);
  59. SDL_FPoint new_head = head_;
  60. switch (direction) {
  61. case Direction::Up:
  62. new_head.y -= distance;
  63. break;
  64. case Direction::Down:
  65. new_head.y += distance;
  66. break;
  67. case Direction::Left:
  68. new_head.x -= distance;
  69. break;
  70. case Direction::Right:
  71. new_head.x += distance;
  72. break;
  73. }
  74. auto const old_pos = ::head_position(head_);
  75. auto const new_pos = ::head_position(new_head);
  76. if (old_pos!=new_pos) {
  77. if (new_direction_.has_value()) {
  78. direction_ = new_direction_.value();
  79. new_direction_.reset();
  80. }
  81. if (new_pos==target_) {
  82. ++length_;
  83. speed_ = std::min(MAX_SPEED, speed_*ACCELERATION);
  84. place_target();
  85. }
  86. if (detect_death(new_pos)) {
  87. gsm.replace_state(GameStates::GameOver);
  88. }
  89. tail_.push_front(old_pos);
  90. if (tail_.size()+1>length_)
  91. tail_.pop_back();
  92. }
  93. head_ = new_head;
  94. }
  95. void PlayingState::handle_direction_change()
  96. {
  97. // this is not done in the event handler as we don't want to wait for KEYUP to re-fire in certain situations
  98. auto const keyboard = SDL_GetKeyboardState(nullptr);
  99. if (keyboard[SDL_SCANCODE_UP] || keyboard[SDL_SCANCODE_W]) {
  100. if (direction_==Direction::Left || direction_==Direction::Right) {
  101. new_direction_ = Direction::Up;
  102. }
  103. }
  104. else if (keyboard[SDL_SCANCODE_DOWN] || keyboard[SDL_SCANCODE_S]) {
  105. if (direction_==Direction::Left || direction_==Direction::Right) {
  106. new_direction_ = Direction::Down;
  107. }
  108. }
  109. else if (keyboard[SDL_SCANCODE_LEFT] || keyboard[SDL_SCANCODE_A]) {
  110. if (direction_==Direction::Up || direction_==Direction::Down) {
  111. new_direction_ = Direction::Left;
  112. }
  113. }
  114. else if (keyboard[SDL_SCANCODE_RIGHT] || keyboard[SDL_SCANCODE_D]) {
  115. if (direction_==Direction::Up || direction_==Direction::Down) {
  116. new_direction_ = Direction::Right;
  117. }
  118. }
  119. }
  120. void PlayingState::render(SDLRenderer& renderer)
  121. {
  122. render_game(renderer);
  123. }
  124. void PlayingState::render_ui(SDLRenderer& renderer, SDL_Rect const& playing_field)
  125. {
  126. TTF_Font* const font = font_;
  127. auto const score_text = std::format("Score: {}", length_);
  128. SDL_Surface* text_surface = TTF_RenderText_Solid(font, score_text.c_str(), {255, 255, 255, SDL_ALPHA_OPAQUE});
  129. SDL_Texture* text = SDL_CreateTextureFromSurface(renderer, text_surface);
  130. SDL_FreeSurface(text_surface);
  131. int text_width, text_height;
  132. SDL_QueryTexture(text, nullptr, nullptr, &text_width, &text_height);
  133. SDL_Rect render_quad = {playing_field.x, 10, text_width, text_height};
  134. SDL_RenderCopy(renderer, text, nullptr, &render_quad);
  135. SDL_DestroyTexture(text);
  136. SDL_SetRenderDrawColor(renderer, 249, 95, 0, SDL_ALPHA_OPAQUE);
  137. SDL_RenderDrawRect(renderer, &playing_field);
  138. }
  139. void PlayingState::place_target()
  140. {
  141. target_.x = distribution_position_x_(generator_);
  142. target_.y = distribution_position_y_(generator_);
  143. }
  144. void PlayingState::place_head()
  145. {
  146. do {
  147. head_.x = static_cast<float>(distribution_position_x_(generator_));
  148. }
  149. while (head_.x<10.0f || head_.x>static_cast<float>(CELLS_X-10));
  150. do {
  151. head_.y = static_cast<float>(distribution_position_y_(generator_));
  152. }
  153. while (head_.y<10.0f || head_.y>static_cast<float>(CELLS_Y-10));
  154. }
  155. void PlayingState::render_target(SDLRenderer& renderer, SDL_Rect const& playing_field)
  156. {
  157. auto const ratio = playing_field.w/static_cast<double>(CELLS_X);
  158. SDL_Rect const target_rect{
  159. .x = static_cast<int>(playing_field.x+ratio*target_.x),
  160. .y = static_cast<int>(playing_field.y+ratio*target_.y),
  161. .w = static_cast<int>(ratio),
  162. .h = static_cast<int>(ratio),
  163. };
  164. SDL_SetRenderDrawColor(renderer, 76, 208, 45, SDL_ALPHA_OPAQUE);
  165. SDL_RenderFillRect(renderer, &target_rect);
  166. }
  167. void PlayingState::render_snake(SDLRenderer& renderer, SDL_Rect const& playing_field)
  168. {
  169. auto const ratio = playing_field.w/static_cast<double>(CELLS_X);
  170. auto const render_dot = [ratio, playing_field, &renderer](SDL_Point const& position, double const size_factor) {
  171. int const base_x = static_cast<int>(playing_field.x+ratio*position.x);
  172. int const base_y = static_cast<int>(playing_field.y+ratio*position.y);
  173. int const size = std::max(1, static_cast<int>(ratio*size_factor));
  174. int const padding = (static_cast<int>(ratio)-size) >> 1;
  175. SDL_Rect const target_rect{
  176. .x = base_x+padding,
  177. .y = base_y+padding,
  178. .w = size,
  179. .h = size,
  180. };
  181. SDL_RenderFillRect(renderer, &target_rect);
  182. };
  183. SDL_SetRenderDrawColor(renderer, 255, 255, 255, SDL_ALPHA_OPAQUE);
  184. double size = 1.0;
  185. double const decay = 1.0/static_cast<double>(tail_.size()+1);
  186. for (auto const& particle: tail_) {
  187. size = std::max(0.0, size-decay);
  188. render_dot(particle, size);
  189. }
  190. SDL_SetRenderDrawColor(renderer, 0, 170, 231, SDL_ALPHA_OPAQUE);
  191. render_dot(::head_position(head_), 1.0);
  192. }
  193. bool PlayingState::detect_death(SDL_Point const& position)
  194. {
  195. // collision with wall
  196. if (position.x<0 || position.x>=CELLS_X || position.y<0 || position.y>=CELLS_Y)
  197. return true;
  198. // collision with self
  199. return (std::ranges::any_of(tail_, [&position](SDL_Point const& particle) {
  200. return position==particle;
  201. }));
  202. }
  203. void PlayingState::render_game(SDLRenderer& renderer, bool is_current_state)
  204. {
  205. int width, height;
  206. SDL_GetRendererOutputSize(renderer, &width, &height);
  207. SDL_Rect playing_field;
  208. double const ratio = static_cast<double>(CELLS_X)/CELLS_Y;
  209. if (width<height*ratio) {
  210. playing_field.w = width-20;
  211. playing_field.h = static_cast<int>(playing_field.w/ratio);
  212. }
  213. else {
  214. playing_field.h = height-70;
  215. playing_field.w = static_cast<int>(playing_field.h*ratio);
  216. }
  217. playing_field.x = (width-playing_field.w)/2;
  218. playing_field.y = 50;
  219. if (is_current_state) {
  220. SDL_SetRenderDrawColor(renderer, 0, 0, 0, SDL_ALPHA_OPAQUE);
  221. SDL_RenderClear(renderer);
  222. }
  223. render_ui(renderer, playing_field);
  224. render_snake(renderer, playing_field);
  225. render_target(renderer, playing_field);
  226. if (is_current_state)
  227. SDL_RenderPresent(renderer);
  228. }