PlayingState.cxx 11 KB

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