PlayingState.cxx 7.5 KB

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