PlayingState.cxx 8.4 KB

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