PlayingState.cxx 9.0 KB

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