PlayingState.cxx 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. #include "PlayingState.hxx"
  2. #include "HighScoreManager.hxx"
  3. #include "GameStateManager.hxx"
  4. #include "TranslationManager.hxx"
  5. #include <algorithm>
  6. #include <cfenv>
  7. #include <cmath>
  8. #include <random>
  9. #include <unordered_set>
  10. namespace std {
  11. template<>
  12. struct hash<SDL_Point> {
  13. std::size_t operator()(SDL_Point const& p) const noexcept
  14. {
  15. static_assert(sizeof(std::size_t)==8u);
  16. static_assert(sizeof(int)==4u);
  17. return (static_cast<std::size_t>(p.x) << 32u) | static_cast<std::size_t>(p.y);
  18. }
  19. };
  20. }
  21. namespace {
  22. SDL_Point head_position(SDL_FPoint const& position)
  23. {
  24. #pragma STDC FENV_ACCESS ON
  25. std::fesetround(FE_TONEAREST);
  26. return {
  27. .x = static_cast<int>(std::nearbyint(position.x)),
  28. .y = static_cast<int>(std::nearbyint(position.y)),
  29. };
  30. }
  31. }
  32. static bool operator==(SDL_Point const& lhs, SDL_Point const& rhs)
  33. {
  34. return lhs.x==rhs.x && lhs.y==rhs.y;
  35. }
  36. static bool operator!=(SDL_Point const& lhs, SDL_Point const& rhs)
  37. {
  38. return lhs.x!=rhs.x || lhs.y!=rhs.y;
  39. }
  40. PlayingState::PlayingState()
  41. :generator_{std::random_device{}()}, font_{"kenney_pixel.ttf"}
  42. {
  43. }
  44. void PlayingState::on_enter(GameStateManager& gsm)
  45. {
  46. (void) gsm;
  47. length_ = 10u;
  48. std::uniform_int_distribution<int> distribution_direction{0, 3};
  49. direction_ = static_cast<Direction>(distribution_direction(generator_));
  50. place_head();
  51. place_target();
  52. tail_.clear();
  53. speed_ = START_SPEED;
  54. }
  55. void PlayingState::on_event(GameStateManager& gsm, SDL_Event const& evt)
  56. {
  57. if (evt.type==SDL_KEYUP) {
  58. auto const scancode = evt.key.keysym.scancode;
  59. if (scancode==SDL_SCANCODE_ESCAPE || scancode==SDL_SCANCODE_PAUSE)
  60. gsm.push_state(GameStates::MainMenu);
  61. }
  62. }
  63. void PlayingState::update(GameStateManager& gsm, std::chrono::milliseconds const delta_time)
  64. {
  65. handle_direction_change();
  66. fps_ = static_cast<int>(1000.0/static_cast<double>(delta_time.count()));
  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& tm = TranslationManager::instance();
  146. auto const score_text = tm.get_translation("Score")+": "+std::to_string(length_);
  147. SDL_Surface* text_surface = TTF_RenderUTF8_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. auto const fps_text = tm.get_translation("Frames per second")+": "+std::to_string(fps_);
  156. text_surface = TTF_RenderUTF8_Solid(font_, fps_text.c_str(), {255, 255, 255, SDL_ALPHA_OPAQUE});
  157. text = SDL_CreateTextureFromSurface(renderer, text_surface);
  158. SDL_FreeSurface(text_surface);
  159. SDL_QueryTexture(text, nullptr, nullptr, &text_width, &text_height);
  160. render_quad = {playing_field.x+playing_field.w-text_width, 10, text_width, text_height};
  161. SDL_RenderCopy(renderer, text, nullptr, &render_quad);
  162. SDL_DestroyTexture(text);
  163. SDL_SetRenderDrawColor(renderer, 249, 95, 0, SDL_ALPHA_OPAQUE);
  164. SDL_RenderDrawRect(renderer, &playing_field);
  165. }
  166. bool PlayingState::place_target()
  167. {
  168. std::unordered_set<SDL_Point> field;
  169. field.reserve(CELLS_X*CELLS_Y);
  170. for (int x = 0; x<CELLS_X; ++x) {
  171. for (int y = 0; y<CELLS_Y; ++y) {
  172. field.insert({x, y});
  173. }
  174. }
  175. for (auto const& particle: tail_) {
  176. field.erase(particle);
  177. }
  178. if (field.empty()) {
  179. return false;
  180. }
  181. std::vector<SDL_Point> result;
  182. std::ranges::sample(field, std::back_inserter(result), 1, generator_);
  183. target_ = result[0];
  184. return true;
  185. }
  186. void PlayingState::place_head()
  187. {
  188. do {
  189. head_.x = static_cast<float>(distribution_position_x_(generator_));
  190. }
  191. while (head_.x<10.0f || head_.x>static_cast<float>(CELLS_X-10));
  192. do {
  193. head_.y = static_cast<float>(distribution_position_y_(generator_));
  194. }
  195. while (head_.y<10.0f || head_.y>static_cast<float>(CELLS_Y-10));
  196. }
  197. void PlayingState::render_target(SDLRenderer& renderer, SDL_Rect const& playing_field)
  198. {
  199. auto const ratio = playing_field.w/static_cast<double>(CELLS_X);
  200. SDL_Rect const target_rect{
  201. .x = static_cast<int>(playing_field.x+ratio*target_.x),
  202. .y = static_cast<int>(playing_field.y+ratio*target_.y),
  203. .w = static_cast<int>(ratio),
  204. .h = static_cast<int>(ratio),
  205. };
  206. SDL_SetRenderDrawColor(renderer, 76, 208, 45, SDL_ALPHA_OPAQUE);
  207. SDL_RenderFillRect(renderer, &target_rect);
  208. }
  209. void PlayingState::render_snake(SDLRenderer& renderer, SDL_Rect const& playing_field)
  210. {
  211. auto const ratio = playing_field.w/static_cast<double>(CELLS_X);
  212. auto const render_dot = [ratio, playing_field, &renderer](SDL_Point const& position, double const size_factor) {
  213. int const base_x = static_cast<int>(playing_field.x+ratio*position.x);
  214. int const base_y = static_cast<int>(playing_field.y+ratio*position.y);
  215. int const size = std::max(1, static_cast<int>(ratio*size_factor));
  216. int const padding = (static_cast<int>(ratio)-size) >> 1;
  217. SDL_Rect const target_rect{
  218. .x = base_x+padding,
  219. .y = base_y+padding,
  220. .w = size,
  221. .h = size,
  222. };
  223. SDL_RenderFillRect(renderer, &target_rect);
  224. };
  225. SDL_SetRenderDrawColor(renderer, 255, 255, 255, SDL_ALPHA_OPAQUE);
  226. double size = 1.0;
  227. double const decay = 1.0/static_cast<double>(tail_.size()+1);
  228. for (auto const& particle: tail_) {
  229. size = std::max(0.0, size-decay);
  230. render_dot(particle, size);
  231. }
  232. SDL_SetRenderDrawColor(renderer, 0, 170, 231, SDL_ALPHA_OPAQUE);
  233. render_dot(::head_position(head_), 1.0);
  234. }
  235. bool PlayingState::detect_death(SDL_Point const& position)
  236. {
  237. // collision with wall
  238. if (position.x<0 || position.x>=CELLS_X || position.y<0 || position.y>=CELLS_Y)
  239. return true;
  240. // collision with self
  241. return (std::ranges::any_of(tail_, [&position](SDL_Point const& particle) {
  242. return position==particle;
  243. }));
  244. }
  245. void PlayingState::render_game(SDLRenderer& renderer, bool is_current_state)
  246. {
  247. int width, height;
  248. SDL_GetRendererOutputSize(renderer, &width, &height);
  249. SDL_Rect playing_field;
  250. double const ratio = static_cast<double>(CELLS_X)/CELLS_Y;
  251. if (width<height*ratio) {
  252. playing_field.w = width-20;
  253. playing_field.h = static_cast<int>(playing_field.w/ratio);
  254. }
  255. else {
  256. playing_field.h = height-70;
  257. playing_field.w = static_cast<int>(playing_field.h*ratio);
  258. }
  259. playing_field.x = (width-playing_field.w)/2;
  260. playing_field.y = 50;
  261. if (is_current_state) {
  262. SDL_SetRenderDrawColor(renderer, 0, 0, 0, SDL_ALPHA_OPAQUE);
  263. SDL_RenderClear(renderer);
  264. }
  265. render_snake(renderer, playing_field);
  266. render_target(renderer, playing_field);
  267. render_ui(renderer, playing_field);
  268. if (is_current_state)
  269. SDL_RenderPresent(renderer);
  270. }