PlayingState.cxx 8.5 KB

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