PlayingState.cxx 12 KB

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