PlayingState.cxx 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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. unsigned PlayingState::last_high_score_{0};
  28. PlayingState::PlayingState()
  29. :generator_{std::random_device{}()}, font_{"kenney_pixel.ttf"}
  30. {
  31. }
  32. void PlayingState::on_enter(GameStateManager& gsm)
  33. {
  34. (void) gsm;
  35. length_ = 10u;
  36. std::uniform_int_distribution<int> distribution_direction{0, 3};
  37. direction_ = static_cast<Direction>(distribution_direction(generator_));
  38. place_head();
  39. place_target();
  40. tail_.clear();
  41. speed_ = START_SPEED;
  42. }
  43. void PlayingState::on_event(GameStateManager& gsm, SDL_Event const& evt)
  44. {
  45. if (evt.type==SDL_KEYUP && evt.key.keysym.scancode==SDL_SCANCODE_ESCAPE) {
  46. gsm.push_state(GameStates::MainMenu);
  47. }
  48. else if (evt.type==SDL_KEYDOWN) {
  49. switch (evt.key.keysym.scancode) {
  50. default:
  51. break;
  52. case SDL_SCANCODE_UP:
  53. if (direction_==Direction::Left || direction_==Direction::Right) {
  54. direction_ = Direction::Up;
  55. }
  56. break;
  57. case SDL_SCANCODE_DOWN:
  58. if (direction_==Direction::Left || direction_==Direction::Right) {
  59. direction_ = Direction::Down;
  60. }
  61. break;
  62. case SDL_SCANCODE_LEFT:
  63. if (direction_==Direction::Up || direction_==Direction::Down) {
  64. direction_ = Direction::Left;
  65. }
  66. break;
  67. case SDL_SCANCODE_RIGHT:
  68. if (direction_==Direction::Up || direction_==Direction::Down) {
  69. direction_ = Direction::Right;
  70. }
  71. break;
  72. }
  73. }
  74. }
  75. void PlayingState::update(GameStateManager& gsm, std::chrono::milliseconds delta_time)
  76. {
  77. auto const distance = speed_*static_cast<float>(delta_time.count());
  78. if (distance>MAX_DISTANCE) {
  79. SDL_Log("Snake would move a distance of %f. Game might have been stuck. Skipping cycle.", distance);
  80. return;
  81. }
  82. SDL_FPoint new_head = head_;
  83. switch (direction_) {
  84. case Direction::Up:
  85. new_head.y -= distance;
  86. break;
  87. case Direction::Down:
  88. new_head.y += distance;
  89. break;
  90. case Direction::Left:
  91. new_head.x -= distance;
  92. break;
  93. case Direction::Right:
  94. new_head.x += distance;
  95. break;
  96. }
  97. auto const old_pos = ::head_position(head_);
  98. auto const new_pos = ::head_position(new_head);
  99. if (old_pos!=new_pos) {
  100. if (new_pos==target_) {
  101. ++length_;
  102. speed_ *= ACCELERATION;
  103. place_target();
  104. }
  105. if (detect_death(new_pos)) {
  106. last_high_score_ = length_;
  107. gsm.replace_state(GameStates::GameOver);
  108. }
  109. tail_.push_front(old_pos);
  110. if (tail_.size()+1>length_)
  111. tail_.pop_back();
  112. }
  113. head_ = new_head;
  114. }
  115. void PlayingState::render(SDLRenderer& renderer)
  116. {
  117. int width, height;
  118. SDL_GetRendererOutputSize(renderer, &width, &height);
  119. SDL_Rect playing_field;
  120. double const ratio = static_cast<double>(CELLS_X)/CELLS_Y;
  121. if (width<height*ratio) {
  122. playing_field.w = width-20;
  123. playing_field.h = static_cast<int>(playing_field.w/ratio);
  124. }
  125. else {
  126. playing_field.h = height-70;
  127. playing_field.w = static_cast<int>(playing_field.h*ratio);
  128. }
  129. playing_field.x = (width-playing_field.w)/2;
  130. playing_field.y = 50;
  131. SDL_SetRenderDrawColor(renderer, 0, 0, 0, SDL_ALPHA_OPAQUE);
  132. SDL_RenderClear(renderer);
  133. render_ui(renderer, playing_field);
  134. render_target(renderer, playing_field);
  135. render_snake(renderer, playing_field);
  136. SDL_RenderPresent(renderer);
  137. }
  138. void PlayingState::render_ui(SDLRenderer& renderer, SDL_Rect const& playing_field)
  139. {
  140. TTF_Font* const font = font_;
  141. auto const score_text = std::format("Score: {}", length_);
  142. SDL_Surface* text_surface = TTF_RenderText_Solid(font, score_text.c_str(), {255, 255, 255, SDL_ALPHA_OPAQUE});
  143. SDL_Texture* text = SDL_CreateTextureFromSurface(renderer, text_surface);
  144. SDL_FreeSurface(text_surface);
  145. int text_width, text_height;
  146. SDL_QueryTexture(text, nullptr, nullptr, &text_width, &text_height);
  147. SDL_Rect render_quad = {playing_field.x, 10, text_width, text_height};
  148. SDL_RenderCopy(renderer, text, nullptr, &render_quad);
  149. SDL_DestroyTexture(text);
  150. SDL_SetRenderDrawColor(renderer, 255, 255, 255, SDL_ALPHA_OPAQUE);
  151. SDL_RenderDrawRect(renderer, &playing_field);
  152. }
  153. void PlayingState::place_target()
  154. {
  155. target_.x = distribution_position_x_(generator_);
  156. target_.y = distribution_position_y_(generator_);
  157. }
  158. void PlayingState::place_head()
  159. {
  160. do {
  161. head_.x = static_cast<float>(distribution_position_x_(generator_));
  162. }
  163. while (head_.x<10.0f || head_.x>static_cast<float>(CELLS_X-10));
  164. do {
  165. head_.y = static_cast<float>(distribution_position_y_(generator_));
  166. }
  167. while (head_.y<10.0f || head_.y>static_cast<float>(CELLS_Y-10));
  168. }
  169. void PlayingState::render_target(SDLRenderer& renderer, SDL_Rect const& playing_field)
  170. {
  171. auto const ratio = playing_field.w/static_cast<double>(CELLS_X);
  172. SDL_Rect const target_rect{
  173. .x = static_cast<int>(playing_field.x+ratio*target_.x),
  174. .y = static_cast<int>(playing_field.y+ratio*target_.y),
  175. .w = static_cast<int>(ratio),
  176. .h = static_cast<int>(ratio),
  177. };
  178. SDL_SetRenderDrawColor(renderer, 0, 255, 0, SDL_ALPHA_OPAQUE);
  179. SDL_RenderFillRect(renderer, &target_rect);
  180. }
  181. void PlayingState::render_snake(SDLRenderer& renderer, SDL_Rect const& playing_field)
  182. {
  183. auto const ratio = playing_field.w/static_cast<double>(CELLS_X);
  184. auto const render_dot = [ratio, playing_field, &renderer](SDL_Point const& position, double const size_factor) {
  185. int const base_x = static_cast<int>(playing_field.x+ratio*position.x);
  186. int const base_y = static_cast<int>(playing_field.y+ratio*position.y);
  187. int const size = std::max(1, static_cast<int>(ratio*size_factor));
  188. int const padding = (static_cast<int>(ratio)-size) >> 1;
  189. SDL_Rect const target_rect{
  190. .x = base_x+padding,
  191. .y = base_y+padding,
  192. .w = size,
  193. .h = size,
  194. };
  195. SDL_RenderFillRect(renderer, &target_rect);
  196. };
  197. SDL_SetRenderDrawColor(renderer, 255, 255, 255, SDL_ALPHA_OPAQUE);
  198. render_dot(::head_position(head_), 1.0);
  199. double size = 1.0;
  200. double const decay = 1.0/static_cast<double>(tail_.size()+1);
  201. for (auto const& particle: tail_) {
  202. size = std::max(0.0, size-decay);
  203. render_dot(particle, size);
  204. }
  205. }
  206. bool PlayingState::detect_death(SDL_Point const& position)
  207. {
  208. // collision with wall
  209. if (position.x<0 || position.x>=CELLS_X || position.y<0 || position.y>=CELLS_Y)
  210. return true;
  211. // collision with self
  212. return (std::ranges::any_of(tail_, [&position](SDL_Point const& particle) {
  213. return position==particle;
  214. }));
  215. }
  216. unsigned PlayingState::last_high_score()
  217. {
  218. return last_high_score_;
  219. }