PlayingState.cxx 9.5 KB

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