PlayingState.cxx 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. #include "PlayingState.hxx"
  2. #include "HighScoreManager.hxx"
  3. #include "GameStateManager.hxx"
  4. #include <algorithm>
  5. #include <cfenv>
  6. #include <cmath>
  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. HighScoreManager::instance().set_new_score(length_);
  101. gsm.replace_state(GameStates::GameOver);
  102. }
  103. }
  104. if (detect_death(new_pos)) {
  105. HighScoreManager::instance().set_new_score(length_);
  106. gsm.replace_state(GameStates::GameOver);
  107. }
  108. tail_.push_front(old_pos);
  109. if (tail_.size()+1>length_)
  110. tail_.pop_back();
  111. }
  112. head_ = new_head;
  113. }
  114. void PlayingState::handle_direction_change()
  115. {
  116. // this is not done in the event handler as we don't want to wait for KEYUP to re-fire in certain situations
  117. auto const keyboard = SDL_GetKeyboardState(nullptr);
  118. if (keyboard[SDL_SCANCODE_UP] || keyboard[SDL_SCANCODE_W]) {
  119. if (direction_==Direction::Left || direction_==Direction::Right) {
  120. new_direction_ = Direction::Up;
  121. }
  122. }
  123. else if (keyboard[SDL_SCANCODE_DOWN] || keyboard[SDL_SCANCODE_S]) {
  124. if (direction_==Direction::Left || direction_==Direction::Right) {
  125. new_direction_ = Direction::Down;
  126. }
  127. }
  128. else if (keyboard[SDL_SCANCODE_LEFT] || keyboard[SDL_SCANCODE_A]) {
  129. if (direction_==Direction::Up || direction_==Direction::Down) {
  130. new_direction_ = Direction::Left;
  131. }
  132. }
  133. else if (keyboard[SDL_SCANCODE_RIGHT] || keyboard[SDL_SCANCODE_D]) {
  134. if (direction_==Direction::Up || direction_==Direction::Down) {
  135. new_direction_ = Direction::Right;
  136. }
  137. }
  138. }
  139. void PlayingState::render(SDLRenderer& renderer)
  140. {
  141. render_game(renderer);
  142. }
  143. void PlayingState::render_ui(SDLRenderer& renderer, SDL_Rect const& playing_field)
  144. {
  145. auto const score_text = "Score: "+std::to_string(length_);
  146. SDL_Surface* text_surface = TTF_RenderText_Solid(font_, score_text.c_str(), {255, 255, 255, SDL_ALPHA_OPAQUE});
  147. SDL_Texture* text = SDL_CreateTextureFromSurface(renderer, text_surface);
  148. SDL_FreeSurface(text_surface);
  149. int text_width, text_height;
  150. SDL_QueryTexture(text, nullptr, nullptr, &text_width, &text_height);
  151. SDL_Rect render_quad = {playing_field.x, 10, text_width, text_height};
  152. SDL_RenderCopy(renderer, text, nullptr, &render_quad);
  153. SDL_DestroyTexture(text);
  154. SDL_SetRenderDrawColor(renderer, 249, 95, 0, SDL_ALPHA_OPAQUE);
  155. SDL_RenderDrawRect(renderer, &playing_field);
  156. }
  157. bool PlayingState::place_target()
  158. {
  159. std::unordered_set<SDL_Point> field;
  160. field.reserve(CELLS_X*CELLS_Y);
  161. for (int x = 0; x<CELLS_X; ++x) {
  162. for (int y = 0; y<CELLS_Y; ++y) {
  163. field.insert({x, y});
  164. }
  165. }
  166. for (auto const& particle: tail_) {
  167. field.erase(particle);
  168. }
  169. if (field.empty()) {
  170. return false;
  171. }
  172. std::vector<SDL_Point> result;
  173. std::ranges::sample(field, std::back_inserter(result), 1, generator_);
  174. target_ = result[0];
  175. return true;
  176. }
  177. void PlayingState::place_head()
  178. {
  179. do {
  180. head_.x = static_cast<float>(distribution_position_x_(generator_));
  181. }
  182. while (head_.x<10.0f || head_.x>static_cast<float>(CELLS_X-10));
  183. do {
  184. head_.y = static_cast<float>(distribution_position_y_(generator_));
  185. }
  186. while (head_.y<10.0f || head_.y>static_cast<float>(CELLS_Y-10));
  187. }
  188. void PlayingState::render_target(SDLRenderer& renderer, SDL_Rect const& playing_field)
  189. {
  190. auto const ratio = playing_field.w/static_cast<double>(CELLS_X);
  191. SDL_Rect const target_rect{
  192. .x = static_cast<int>(playing_field.x+ratio*target_.x),
  193. .y = static_cast<int>(playing_field.y+ratio*target_.y),
  194. .w = static_cast<int>(ratio),
  195. .h = static_cast<int>(ratio),
  196. };
  197. SDL_SetRenderDrawColor(renderer, 76, 208, 45, SDL_ALPHA_OPAQUE);
  198. SDL_RenderFillRect(renderer, &target_rect);
  199. }
  200. void PlayingState::render_snake(SDLRenderer& renderer, SDL_Rect const& playing_field)
  201. {
  202. auto const ratio = playing_field.w/static_cast<double>(CELLS_X);
  203. auto const render_dot = [ratio, playing_field, &renderer](SDL_Point const& position, double const size_factor) {
  204. int const base_x = static_cast<int>(playing_field.x+ratio*position.x);
  205. int const base_y = static_cast<int>(playing_field.y+ratio*position.y);
  206. int const size = std::max(1, static_cast<int>(ratio*size_factor));
  207. int const padding = (static_cast<int>(ratio)-size) >> 1;
  208. SDL_Rect const target_rect{
  209. .x = base_x+padding,
  210. .y = base_y+padding,
  211. .w = size,
  212. .h = size,
  213. };
  214. SDL_RenderFillRect(renderer, &target_rect);
  215. };
  216. SDL_SetRenderDrawColor(renderer, 255, 255, 255, SDL_ALPHA_OPAQUE);
  217. double size = 1.0;
  218. double const decay = 1.0/static_cast<double>(tail_.size()+1);
  219. for (auto const& particle: tail_) {
  220. size = std::max(0.0, size-decay);
  221. render_dot(particle, size);
  222. }
  223. SDL_SetRenderDrawColor(renderer, 0, 170, 231, SDL_ALPHA_OPAQUE);
  224. render_dot(::head_position(head_), 1.0);
  225. }
  226. bool PlayingState::detect_death(SDL_Point const& position)
  227. {
  228. // collision with wall
  229. if (position.x<0 || position.x>=CELLS_X || position.y<0 || position.y>=CELLS_Y)
  230. return true;
  231. // collision with self
  232. return (std::ranges::any_of(tail_, [&position](SDL_Point const& particle) {
  233. return position==particle;
  234. }));
  235. }
  236. void PlayingState::render_game(SDLRenderer& renderer, bool is_current_state)
  237. {
  238. int width, height;
  239. SDL_GetRendererOutputSize(renderer, &width, &height);
  240. SDL_Rect playing_field;
  241. double const ratio = static_cast<double>(CELLS_X)/CELLS_Y;
  242. if (width<height*ratio) {
  243. playing_field.w = width-20;
  244. playing_field.h = static_cast<int>(playing_field.w/ratio);
  245. }
  246. else {
  247. playing_field.h = height-70;
  248. playing_field.w = static_cast<int>(playing_field.h*ratio);
  249. }
  250. playing_field.x = (width-playing_field.w)/2;
  251. playing_field.y = 50;
  252. if (is_current_state) {
  253. SDL_SetRenderDrawColor(renderer, 0, 0, 0, SDL_ALPHA_OPAQUE);
  254. SDL_RenderClear(renderer);
  255. }
  256. render_snake(renderer, playing_field);
  257. render_target(renderer, playing_field);
  258. render_ui(renderer, playing_field);
  259. if (is_current_state)
  260. SDL_RenderPresent(renderer);
  261. }