PlayingState.cxx 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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. auto const MAX_X = static_cast<float>(CELLS_X-1);
  74. auto const MAX_Y = static_cast<float>(CELLS_Y-1);
  75. SDL_FPoint new_head = head_;
  76. switch (direction) {
  77. case Direction::Up:
  78. new_head.y -= distance;
  79. if (new_head.y<0.0f && !deadly_wall_) {
  80. new_head.y += MAX_Y;
  81. }
  82. break;
  83. case Direction::Down:
  84. new_head.y += distance;
  85. if (new_head.y>=MAX_Y && !deadly_wall_) {
  86. new_head.y -= MAX_Y;
  87. }
  88. break;
  89. case Direction::Left:
  90. new_head.x -= distance;
  91. if (new_head.x<0.0f && !deadly_wall_) {
  92. new_head.x += MAX_X;
  93. }
  94. break;
  95. case Direction::Right:
  96. new_head.x += distance;
  97. if (new_head.x>=MAX_X && !deadly_wall_) {
  98. new_head.x -= MAX_X;
  99. }
  100. break;
  101. }
  102. auto const old_pos = ::head_position(head_);
  103. auto const new_pos = ::head_position(new_head);
  104. if (old_pos!=new_pos) {
  105. if (new_direction_.has_value()) {
  106. direction_ = new_direction_.value();
  107. new_direction_.reset();
  108. }
  109. if (detect_death(new_pos)) {
  110. HighScoreManager::instance().set_new_score(length_);
  111. gsm.replace_state(GameStates::GameOver);
  112. }
  113. if (new_pos==target_) {
  114. ++length_;
  115. speed_ = std::min(MAX_SPEED, speed_*ACCELERATION);
  116. if (!place_target()) {
  117. // technically the player finished the game at this point
  118. HighScoreManager::instance().set_new_score(length_);
  119. gsm.replace_state(GameStates::GameOver);
  120. }
  121. }
  122. tail_.push_front(old_pos);
  123. if (tail_.size()+1>length_)
  124. tail_.pop_back();
  125. }
  126. head_ = new_head;
  127. }
  128. void PlayingState::handle_direction_change()
  129. {
  130. // this is not done in the event handler as we don't want to wait for KEYUP to re-fire in certain situations
  131. auto const keyboard = SDL_GetKeyboardState(nullptr);
  132. if (new_direction_.has_value())
  133. return;
  134. if (direction_==Direction::Left || direction_==Direction::Right) {
  135. if (keyboard[SDL_SCANCODE_UP] || keyboard[SDL_SCANCODE_W]) {
  136. new_direction_ = Direction::Up;
  137. }
  138. else if (keyboard[SDL_SCANCODE_DOWN] || keyboard[SDL_SCANCODE_S]) {
  139. new_direction_ = Direction::Down;
  140. }
  141. }
  142. else {
  143. if (keyboard[SDL_SCANCODE_LEFT] || keyboard[SDL_SCANCODE_A]) {
  144. new_direction_ = Direction::Left;
  145. }
  146. else if (keyboard[SDL_SCANCODE_RIGHT] || keyboard[SDL_SCANCODE_D]) {
  147. new_direction_ = Direction::Right;
  148. }
  149. }
  150. }
  151. void PlayingState::render(SDLRenderer& renderer)
  152. {
  153. render_game(renderer);
  154. }
  155. void PlayingState::render_ui(SDLRenderer& renderer, SDL_Rect const& playing_field)
  156. {
  157. auto const& tm = TranslationManager::instance();
  158. auto const score_text = tm.get_translation("Score")+": "+std::to_string(length_);
  159. SDL_Surface* text_surface = TTF_RenderUTF8_Solid(font_, score_text.c_str(), {255, 255, 255, SDL_ALPHA_OPAQUE});
  160. SDL_Texture* text = SDL_CreateTextureFromSurface(renderer, text_surface);
  161. SDL_FreeSurface(text_surface);
  162. int text_width, text_height;
  163. SDL_QueryTexture(text, nullptr, nullptr, &text_width, &text_height);
  164. SDL_Rect render_quad = {playing_field.x, 10, text_width, text_height};
  165. SDL_RenderCopy(renderer, text, nullptr, &render_quad);
  166. SDL_DestroyTexture(text);
  167. auto const fps_text = tm.get_translation("Frames per second")+": "+std::to_string(fps_);
  168. text_surface = TTF_RenderUTF8_Solid(font_, fps_text.c_str(), {255, 255, 255, SDL_ALPHA_OPAQUE});
  169. text = SDL_CreateTextureFromSurface(renderer, text_surface);
  170. SDL_FreeSurface(text_surface);
  171. SDL_QueryTexture(text, nullptr, nullptr, &text_width, &text_height);
  172. render_quad = {playing_field.x+playing_field.w-text_width, 10, text_width, text_height};
  173. SDL_RenderCopy(renderer, text, nullptr, &render_quad);
  174. SDL_DestroyTexture(text);
  175. if (deadly_wall_)
  176. SDL_SetRenderDrawColor(renderer, 249, 95, 0, SDL_ALPHA_OPAQUE);
  177. else
  178. SDL_SetRenderDrawColor(renderer, 255, 204, 0, SDL_ALPHA_OPAQUE);
  179. SDL_RenderDrawRect(renderer, &playing_field);
  180. }
  181. bool PlayingState::place_target()
  182. {
  183. std::unordered_set<SDL_Point> field;
  184. field.reserve(CELLS_X*CELLS_Y);
  185. for (int x = 0; x<CELLS_X; ++x) {
  186. for (int y = 0; y<CELLS_Y; ++y) {
  187. field.insert({x, y});
  188. }
  189. }
  190. field.erase(::head_position(head_));
  191. for (auto const& particle: tail_) {
  192. field.erase(particle);
  193. }
  194. if (field.empty()) {
  195. return false;
  196. }
  197. std::vector<SDL_Point> result;
  198. std::ranges::sample(field, std::back_inserter(result), 1, generator_);
  199. target_ = result[0];
  200. deadly_wall_ = distribution_deadly_wall(generator_)!=0;
  201. return true;
  202. }
  203. void PlayingState::place_head()
  204. {
  205. do {
  206. head_.x = static_cast<float>(distribution_position_x_(generator_));
  207. }
  208. while (head_.x<10.0f || head_.x>static_cast<float>(CELLS_X-10));
  209. do {
  210. head_.y = static_cast<float>(distribution_position_y_(generator_));
  211. }
  212. while (head_.y<10.0f || head_.y>static_cast<float>(CELLS_Y-10));
  213. }
  214. void PlayingState::render_target(SDLRenderer& renderer, SDL_Rect const& playing_field)
  215. {
  216. auto const ratio = playing_field.w/static_cast<double>(CELLS_X);
  217. SDL_Rect const target_rect{
  218. .x = static_cast<int>(playing_field.x+ratio*target_.x),
  219. .y = static_cast<int>(playing_field.y+ratio*target_.y),
  220. .w = static_cast<int>(ratio),
  221. .h = static_cast<int>(ratio),
  222. };
  223. SDL_SetRenderDrawColor(renderer, 76, 208, 45, SDL_ALPHA_OPAQUE);
  224. SDL_RenderFillRect(renderer, &target_rect);
  225. }
  226. void PlayingState::render_snake(SDLRenderer& renderer, SDL_Rect const& playing_field)
  227. {
  228. auto const ratio = playing_field.w/static_cast<double>(CELLS_X);
  229. auto const render_dot = [ratio, playing_field, &renderer](SDL_Point const& position, double const size_factor) {
  230. int const base_x = static_cast<int>(playing_field.x+ratio*position.x);
  231. int const base_y = static_cast<int>(playing_field.y+ratio*position.y);
  232. int const size = std::max(1, static_cast<int>(ratio*size_factor));
  233. int const padding = (static_cast<int>(ratio)-size) >> 1;
  234. SDL_Rect const target_rect{
  235. .x = base_x+padding,
  236. .y = base_y+padding,
  237. .w = size,
  238. .h = size,
  239. };
  240. SDL_RenderFillRect(renderer, &target_rect);
  241. };
  242. SDL_SetRenderDrawColor(renderer, 255, 255, 255, SDL_ALPHA_OPAQUE);
  243. double size = 1.0;
  244. double const decay = 1.0/static_cast<double>(tail_.size()+1);
  245. for (auto const& particle: tail_) {
  246. size = std::max(0.0, size-decay);
  247. render_dot(particle, size);
  248. }
  249. SDL_SetRenderDrawColor(renderer, 0, 170, 231, SDL_ALPHA_OPAQUE);
  250. render_dot(::head_position(head_), 1.0);
  251. }
  252. bool PlayingState::detect_death(SDL_Point const& position)
  253. {
  254. // collision with wall
  255. if (position.x<0 || position.x>=CELLS_X || position.y<0 || position.y>=CELLS_Y)
  256. return true;
  257. // collision with self
  258. return (std::ranges::any_of(tail_, [&position](SDL_Point const& particle) {
  259. return position==particle;
  260. }));
  261. }
  262. void PlayingState::render_game(SDLRenderer& renderer, bool is_current_state)
  263. {
  264. int width, height;
  265. SDL_GetRendererOutputSize(renderer, &width, &height);
  266. SDL_Rect playing_field;
  267. double const ratio = static_cast<double>(CELLS_X)/CELLS_Y;
  268. if (width<height*ratio) {
  269. playing_field.w = width-20;
  270. playing_field.h = static_cast<int>(playing_field.w/ratio);
  271. }
  272. else {
  273. playing_field.h = height-70;
  274. playing_field.w = static_cast<int>(playing_field.h*ratio);
  275. }
  276. playing_field.x = (width-playing_field.w)/2;
  277. playing_field.y = 50;
  278. if (is_current_state) {
  279. SDL_SetRenderDrawColor(renderer, 0, 0, 0, SDL_ALPHA_OPAQUE);
  280. SDL_RenderClear(renderer);
  281. }
  282. render_snake(renderer, playing_field);
  283. render_target(renderer, playing_field);
  284. render_ui(renderer, playing_field);
  285. if (is_current_state)
  286. SDL_RenderPresent(renderer);
  287. }