app.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775
  1. /* Copyright (C) 2023 Salvatore Sanfilippo -- All Rights Reserved
  2. * See the LICENSE file for information about the license. */
  3. #include <furi.h>
  4. #include <furi_hal.h>
  5. #include <storage/storage.h>
  6. #include <input/input.h>
  7. #include <gui/gui.h>
  8. #include <stdlib.h>
  9. #include <gui/gui.h>
  10. #include <gui/view_dispatcher.h>
  11. #include <gui/scene_manager.h>
  12. #include <math.h>
  13. #include <notification/notification.h>
  14. #include <notification/notification_messages.h>
  15. #define TAG "Asteroids" // Used for logging
  16. #define DEBUG_MSG 1
  17. #define SCREEN_XRES 128
  18. #define SCREEN_YRES 64
  19. #define GAME_START_LIVES 3
  20. #define TTLBUL 30 /* Bullet time to live, in ticks. */
  21. #define MAXBUL 5 /* Max bullets on the screen. */
  22. #define MAXAST 32 /* Max asteroids on the screen. */
  23. #define SHIP_HIT_ANIMATION_LEN 15
  24. #define SAVING_DIRECTORY "/ext/apps/Games"
  25. #define SAVING_FILENAME SAVING_DIRECTORY "/game_asteroids.save"
  26. #ifndef PI
  27. #define PI 3.14159265358979f
  28. #endif
  29. /* ============================ Data structures ============================= */
  30. typedef struct Ship {
  31. float x, /* Ship x position. */
  32. y, /* Ship y position. */
  33. vx, /* x velocity. */
  34. vy, /* y velocity. */
  35. rot; /* Current rotation. 2*PI full ortation. */
  36. } Ship;
  37. typedef struct Bullet {
  38. float x, y, vx, vy; /* Fields like in ship. */
  39. uint32_t ttl; /* Time to live, in ticks. */
  40. } Bullet;
  41. typedef struct Asteroid {
  42. float x, y, vx, vy, rot, /* Fields like ship. */
  43. rot_speed, /* Angular velocity (rot speed and sense). */
  44. size; /* Asteroid size. */
  45. uint8_t shape_seed; /* Seed to give random shape. */
  46. } Asteroid;
  47. typedef struct AsteroidsApp {
  48. /* GUI */
  49. Gui* gui;
  50. ViewPort* view_port; /* We just use a raw viewport and we render
  51. everything into the low level canvas. */
  52. FuriMessageQueue* event_queue; /* Keypress events go here. */
  53. /* Game state. */
  54. int running; /* Once false exists the app. */
  55. bool gameover; /* Gameover status. */
  56. uint32_t ticks; /* Game ticks. Increments at each refresh. */
  57. uint32_t score; /* Game score. */
  58. uint32_t highscore; /* Highscore. Shown on Game Over Screen */
  59. uint32_t last_score; /* Last score. Shown on Game Over screen */
  60. bool is_new_highscore; /* Is the last score a new highscore? */
  61. uint32_t lives; /* Number of lives in the current game. */
  62. uint32_t ship_hit; /* When non zero, the ship was hit by an asteroid
  63. and we need to show an animation as long as
  64. its value is non-zero (and decrease it's value
  65. at each tick of animation). */
  66. /* Ship state. */
  67. struct Ship ship;
  68. /* Bullets state. */
  69. struct Bullet bullets[MAXBUL]; /* Each bullet state. */
  70. int bullets_num; /* Active bullets. */
  71. uint32_t last_bullet_tick; /* Tick the last bullet was fired. */
  72. /* Asteroids state. */
  73. Asteroid asteroids[MAXAST]; /* Each asteroid state. */
  74. int asteroids_num; /* Active asteroids. */
  75. uint32_t pressed[InputKeyMAX]; /* pressed[id] is true if pressed.
  76. Each array item contains the time
  77. in milliseconds the key was pressed. */
  78. bool fire; /* Short press detected: fire a bullet. */
  79. } AsteroidsApp;
  80. const NotificationSequence sequence_crash = {
  81. &message_red_255,
  82. &message_vibro_on,
  83. // &message_note_g5, // Play sound but currently disabled
  84. &message_delay_25,
  85. // &message_note_e5,
  86. &message_vibro_off,
  87. &message_sound_off,
  88. NULL,
  89. };
  90. const NotificationSequence sequence_bullet_fired = {
  91. &message_vibro_on,
  92. // &message_note_g5, // Play sound but currently disabled. Need On/Off menu setting
  93. &message_delay_10,
  94. &message_delay_1,
  95. &message_delay_1,
  96. &message_delay_1,
  97. &message_delay_1,
  98. &message_delay_1,
  99. // &message_note_e5,
  100. &message_vibro_off,
  101. &message_sound_off,
  102. NULL,
  103. };
  104. /* ============================== Prototyeps ================================ */
  105. // Only functions called before their definition are here.
  106. bool load_game(AsteroidsApp* app);
  107. void save_game(AsteroidsApp* app);
  108. void restart_game_after_gameover(AsteroidsApp* app);
  109. uint32_t key_pressed_time(AsteroidsApp* app, InputKey key);
  110. /* ============================ 2D drawing ================================== */
  111. /* This structure represents a polygon of at most POLY_MAX points.
  112. * The function draw_poly() is able to render it on the screen, rotated
  113. * by the amount specified. */
  114. #define POLY_MAX 8
  115. typedef struct Poly {
  116. float x[POLY_MAX];
  117. float y[POLY_MAX];
  118. uint32_t points; /* Number of points actually populated. */
  119. } Poly;
  120. /* Define the polygons we use. */
  121. Poly ShipPoly = {{-3, 0, 3}, {-3, 6, -3}, 3};
  122. Poly ShipFirePoly = {{-1.5, 0, 1.5}, {-3, -6, -3}, 3};
  123. /* Rotate the point of the poligon 'poly' and store the new rotated
  124. * polygon in 'rot'. The polygon is rotated by an angle 'a', with
  125. * center at 0,0. */
  126. void rotate_poly(Poly* rot, Poly* poly, float a) {
  127. /* We want to compute sin(a) and cos(a) only one time
  128. * for every point to rotate. It's a slow operation. */
  129. float sin_a = (float)sin(a);
  130. float cos_a = (float)cos(a);
  131. for(uint32_t j = 0; j < poly->points; j++) {
  132. rot->x[j] = poly->x[j] * cos_a - poly->y[j] * sin_a;
  133. rot->y[j] = poly->y[j] * cos_a + poly->x[j] * sin_a;
  134. }
  135. rot->points = poly->points;
  136. }
  137. /* This is an 8 bit LFSR we use to generate a predictable and fast
  138. * pseudorandom sequence of numbers, to give a different shape to
  139. * each asteroid. */
  140. void lfsr_next(unsigned char* prev) {
  141. unsigned char lsb = *prev & 1;
  142. *prev = *prev >> 1;
  143. if(lsb == 1) *prev ^= 0b11000111;
  144. *prev ^= *prev << 7; /* Mix things a bit more. */
  145. }
  146. /* Render the polygon 'poly' at x,y, rotated by the specified angle. */
  147. void draw_poly(Canvas* const canvas, Poly* poly, uint8_t x, uint8_t y, float a) {
  148. Poly rot;
  149. rotate_poly(&rot, poly, a);
  150. canvas_set_color(canvas, ColorBlack);
  151. for(uint32_t j = 0; j < rot.points; j++) {
  152. uint32_t a = j;
  153. uint32_t b = j + 1;
  154. if(b == rot.points) b = 0;
  155. canvas_draw_line(canvas, x + rot.x[a], y + rot.y[a], x + rot.x[b], y + rot.y[b]);
  156. }
  157. }
  158. /* A bullet is just a + pixels pattern. A single pixel is not
  159. * visible enough. */
  160. void draw_bullet(Canvas* const canvas, Bullet* b) {
  161. canvas_draw_dot(canvas, b->x - 1, b->y);
  162. canvas_draw_dot(canvas, b->x + 1, b->y);
  163. canvas_draw_dot(canvas, b->x, b->y);
  164. canvas_draw_dot(canvas, b->x, b->y - 1);
  165. canvas_draw_dot(canvas, b->x, b->y + 1);
  166. }
  167. /* Draw an asteroid. The asteroid shapes is computed on the fly and
  168. * is not stored in a permanent shape structure. In order to generate
  169. * the shape, we use an initial fixed shape that we resize according
  170. * to the asteroid size, perturbate according to the asteroid shape
  171. * seed, and finally draw it rotated of the right amount. */
  172. void draw_asteroid(Canvas* const canvas, Asteroid* ast) {
  173. Poly ap;
  174. /* Start with what is kinda of a circle. Note that this could be
  175. * stored into a template and copied here, to avoid computing
  176. * sin() / cos(). But the Flipper can handle it without problems. */
  177. uint8_t r = ast->shape_seed;
  178. for(int j = 0; j < 8; j++) {
  179. float a = (PI * 2) / 8 * j;
  180. /* Before generating the point, to make the shape unique generate
  181. * a random factor between .7 and 1.3 to scale the distance from
  182. * the center. However this asteroid should have its unique shape
  183. * that remains always the same, so we use a predictable PRNG
  184. * implemented by an 8 bit shift register. */
  185. lfsr_next(&r);
  186. float scaling = .7 + ((float)r / 255 * .6);
  187. ap.x[j] = (float)sin(a) * ast->size * scaling;
  188. ap.y[j] = (float)cos(a) * ast->size * scaling;
  189. }
  190. ap.points = 8;
  191. draw_poly(canvas, &ap, ast->x, ast->y, ast->rot);
  192. }
  193. /* Draw small ships in the top-right part of the screen, one for
  194. * each left live. */
  195. void draw_left_lives(Canvas* const canvas, AsteroidsApp* app) {
  196. int lives = app->lives;
  197. int x = SCREEN_XRES - 5;
  198. Poly mini_ship = {{-2, 0, 2}, {-2, 4, -2}, 3};
  199. while(lives--) {
  200. draw_poly(canvas, &mini_ship, x, 6, PI);
  201. x -= 6;
  202. }
  203. }
  204. /* Given the current position, update it according to the velocity and
  205. * wrap it back to the other side if the object went over the screen. */
  206. void update_pos_by_velocity(float* x, float* y, float vx, float vy) {
  207. /* Return back from one side to the other of the screen. */
  208. *x += vx;
  209. *y += vy;
  210. if(*x >= SCREEN_XRES)
  211. *x = 0;
  212. else if(*x < 0)
  213. *x = SCREEN_XRES - 1;
  214. if(*y >= SCREEN_YRES)
  215. *y = 0;
  216. else if(*y < 0)
  217. *y = SCREEN_YRES - 1;
  218. }
  219. /* Render the current game screen. */
  220. void render_callback(Canvas* const canvas, void* ctx) {
  221. AsteroidsApp* app = ctx;
  222. /* Clear screen. */
  223. canvas_set_color(canvas, ColorWhite);
  224. canvas_draw_box(canvas, 0, 0, SCREEN_XRES - 1, SCREEN_YRES - 1);
  225. /* Draw score. */
  226. canvas_set_color(canvas, ColorBlack);
  227. canvas_set_font(canvas, FontSecondary);
  228. char score[32];
  229. snprintf(score, sizeof(score), "%lu", app->score);
  230. canvas_draw_str(canvas, 0, 8, score);
  231. /* Draw left ships. */
  232. draw_left_lives(canvas, app);
  233. /* Draw ship, asteroids, bullets. */
  234. draw_poly(canvas, &ShipPoly, app->ship.x, app->ship.y, app->ship.rot);
  235. if(key_pressed_time(app, InputKeyUp) > 0) {
  236. draw_poly(canvas, &ShipFirePoly, app->ship.x, app->ship.y, app->ship.rot);
  237. }
  238. for(int j = 0; j < app->bullets_num; j++) draw_bullet(canvas, &app->bullets[j]);
  239. for(int j = 0; j < app->asteroids_num; j++) draw_asteroid(canvas, &app->asteroids[j]);
  240. /* Game over text. */
  241. if(app->gameover) {
  242. canvas_set_color(canvas, ColorBlack);
  243. canvas_set_font(canvas, FontPrimary);
  244. // TODO: if new highscore, display blinking "New High Score"
  245. // Display High Score
  246. if(app->is_new_highscore) {
  247. canvas_draw_str(canvas, 22, 9, "New High Score!");
  248. } else {
  249. canvas_draw_str(canvas, 36, 9, "High Score");
  250. }
  251. // Convert highscore to string
  252. int length = snprintf(NULL, 0, "%lu", app->highscore);
  253. char* str_high_score = malloc(length + 1);
  254. snprintf(str_high_score, length + 1, "%lu", app->highscore);
  255. // Get length to center on screen
  256. int nDigits = 0;
  257. if(app->highscore > 0) {
  258. nDigits = floor(log10(app->highscore)) + 1;
  259. }
  260. // Draw highscore centered
  261. canvas_draw_str(canvas, (SCREEN_XRES / 2) - (nDigits * 2), 18, str_high_score);
  262. free(str_high_score);
  263. canvas_draw_str(canvas, 28, 35, "GAME OVER");
  264. canvas_set_font(canvas, FontSecondary);
  265. canvas_draw_str(canvas, 25, 50, "Press OK to restart");
  266. }
  267. }
  268. /* ============================ Game logic ================================== */
  269. float distance(float x1, float y1, float x2, float y2) {
  270. float dx = x1 - x2;
  271. float dy = y1 - y2;
  272. return sqrt(dx * dx + dy * dy);
  273. }
  274. /* Detect a collision between the object at x1,y1 of radius r1 and
  275. * the object at x2, y2 of radius r2. A factor < 1 will make the
  276. * function detect the collision even if the objects are yet not
  277. * relly touching, while a factor > 1 will make it detect the collision
  278. * only after they are a bit overlapping. It basically is used to
  279. * rescale the distance.
  280. *
  281. * Note that in this simplified 2D world, objects are all considered
  282. * spheres (this is why this function only takes the radius). This
  283. * is, after all, kinda accurate for asteroids, for bullets, and
  284. * even for the ship "core" itself. */
  285. bool objects_are_colliding(float x1, float y1, float r1, float x2, float y2, float r2, float factor) {
  286. /* The objects are colliding if the distance between object 1 and 2
  287. * is smaller than the sum of the two radiuses r1 and r2.
  288. * So it would be like: sqrt((x1-x2)^2+(y1-y2)^2) < r1+r2.
  289. * However we can avoid computing the sqrt (which is slow) by
  290. * squaring the second term and removing the square root, making
  291. * the comparison like this:
  292. *
  293. * (x1-x2)^2+(y1-y2)^2 < (r1+r2)^2. */
  294. float dx = (x1 - x2) * factor;
  295. float dy = (y1 - y2) * factor;
  296. float rsum = r1 + r2;
  297. return dx * dx + dy * dy < rsum * rsum;
  298. }
  299. /* Create a new bullet headed in the same direction of the ship. */
  300. void ship_fire_bullet(AsteroidsApp* app) {
  301. if(app->bullets_num == MAXBUL) return;
  302. notification_message(furi_record_open(RECORD_NOTIFICATION), &sequence_bullet_fired);
  303. Bullet* b = &app->bullets[app->bullets_num];
  304. b->x = app->ship.x;
  305. b->y = app->ship.y;
  306. b->vx = -sin(app->ship.rot);
  307. b->vy = cos(app->ship.rot);
  308. /* Ship should fire from its head, not in the middle. */
  309. b->x += b->vx * 5;
  310. b->y += b->vy * 5;
  311. /* Give the bullet some velocity (for now the vector is just
  312. * normalized to 1). */
  313. b->vx *= 3;
  314. b->vy *= 3;
  315. /* It's more realistic if we add the velocity vector of the
  316. * ship, too. Otherwise if the ship is going fast the bullets
  317. * will be slower, which is not how the world works. */
  318. b->vx += app->ship.vx;
  319. b->vy += app->ship.vy;
  320. b->ttl = TTLBUL; /* The bullet will disappear after N ticks. */
  321. app->bullets_num++;
  322. }
  323. /* Remove the specified bullet by id (index in the array). */
  324. void remove_bullet(AsteroidsApp* app, int bid) {
  325. /* Replace the top bullet with the empty space left
  326. * by the removal of this bullet. This way we always take the
  327. * array dense, which is an advantage when looping. */
  328. int n = --app->bullets_num;
  329. if(n && bid != n) app->bullets[bid] = app->bullets[n];
  330. }
  331. /* Create a new asteroid, away from the ship. Return the
  332. * pointer to the asteroid object, so that the caller can change
  333. * certain things of the asteroid if needed. */
  334. Asteroid* add_asteroid(AsteroidsApp* app) {
  335. if(app->asteroids_num == MAXAST) return NULL;
  336. float size = 4 + rand() % 15;
  337. float min_distance = 20;
  338. float x, y;
  339. do {
  340. x = rand() % SCREEN_XRES;
  341. y = rand() % SCREEN_YRES;
  342. } while(distance(app->ship.x, app->ship.y, x, y) < min_distance + size);
  343. Asteroid* a = &app->asteroids[app->asteroids_num++];
  344. a->x = x;
  345. a->y = y;
  346. a->vx = 2 * (-.5 + ((float)rand() / RAND_MAX));
  347. a->vy = 2 * (-.5 + ((float)rand() / RAND_MAX));
  348. a->size = size;
  349. a->rot = 0;
  350. a->rot_speed = ((float)rand() / RAND_MAX) / 10;
  351. if(app->ticks & 1) a->rot_speed = -(a->rot_speed);
  352. a->shape_seed = rand() & 255;
  353. return a;
  354. }
  355. /* Remove the specified asteroid by id (index in the array). */
  356. void remove_asteroid(AsteroidsApp* app, int id) {
  357. /* Replace the top asteroid with the empty space left
  358. * by the removal of this one. This way we always take the
  359. * array dense, which is an advantage when looping. */
  360. int n = --app->asteroids_num;
  361. if(n && id != n) app->asteroids[id] = app->asteroids[n];
  362. }
  363. /* Called when an asteroid was reached by a bullet. The asteroid
  364. * hit is the one with the specified 'id'. */
  365. void asteroid_was_hit(AsteroidsApp* app, int id) {
  366. float sizelimit = 6; // Smaller than that polverize in one shot.
  367. Asteroid* a = &app->asteroids[id];
  368. /* Asteroid is large enough to break into fragments. */
  369. float size = a->size;
  370. float x = a->x, y = a->y;
  371. remove_asteroid(app, id);
  372. if(size > sizelimit) {
  373. int max_fragments = size / sizelimit;
  374. int fragments = 2 + rand() % max_fragments;
  375. float newsize = size / fragments;
  376. if(newsize < 2) newsize = 2;
  377. for(int j = 0; j < fragments; j++) {
  378. a = add_asteroid(app);
  379. if(a == NULL) break; // Too many asteroids on screen.
  380. a->x = x + -(size / 2) + rand() % (int)newsize;
  381. a->y = y + -(size / 2) + rand() % (int)newsize;
  382. a->size = newsize;
  383. }
  384. } else {
  385. app->score++;
  386. app->last_score = app->score; // Save for Game Over Screen
  387. if(app->score > app->highscore) {
  388. app->is_new_highscore = true;
  389. app->highscore = app->score; // Show on Game Over Screen and future main menu
  390. }
  391. }
  392. }
  393. /* Set gameover state. When in game-over mode, the game displays a gameover
  394. * text with a background of many asteroids floating around. */
  395. void game_over(AsteroidsApp* app) {
  396. save_game(app); // Save highscore
  397. restart_game_after_gameover(app);
  398. app->gameover = true;
  399. app->score = app->last_score;
  400. app->lives = GAME_START_LIVES; // Show 3 lives in game over screen to match new game start
  401. int asteroids = 8;
  402. while(asteroids-- && add_asteroid(app) != NULL)
  403. ;
  404. }
  405. /* Function called when a collision between the asteroid and the
  406. * ship is detected. */
  407. void ship_was_hit(AsteroidsApp* app) {
  408. app->ship_hit = SHIP_HIT_ANIMATION_LEN;
  409. if(app->lives) {
  410. app->lives--;
  411. } else {
  412. game_over(app);
  413. }
  414. }
  415. /* Restart game after the ship is hit. Will reset the ship position, bullets
  416. * and asteroids to restart the game. */
  417. void restart_game(AsteroidsApp* app) {
  418. app->ship.x = SCREEN_XRES / 2;
  419. app->ship.y = SCREEN_YRES / 2;
  420. app->ship.rot = PI; /* Start headed towards top. */
  421. app->ship.vx = 0;
  422. app->ship.vy = 0;
  423. app->bullets_num = 0;
  424. app->last_bullet_tick = 0;
  425. app->asteroids_num = 0;
  426. }
  427. /* Called after gameover to restart the game. This function
  428. * also calls restart_game(). */
  429. void restart_game_after_gameover(AsteroidsApp* app) {
  430. app->is_new_highscore = false;
  431. app->gameover = false;
  432. app->ticks = 0;
  433. app->score = 0;
  434. app->ship_hit = 0;
  435. app->lives = GAME_START_LIVES - 1;
  436. restart_game(app);
  437. }
  438. /* Move bullets. */
  439. void update_bullets_position(AsteroidsApp* app) {
  440. for(int j = 0; j < app->bullets_num; j++) {
  441. update_pos_by_velocity(
  442. &app->bullets[j].x, &app->bullets[j].y, app->bullets[j].vx, app->bullets[j].vy);
  443. if(--app->bullets[j].ttl == 0) {
  444. remove_bullet(app, j);
  445. j--; /* Process this bullet index again: the removal will
  446. fill it with the top bullet to take the array dense. */
  447. }
  448. }
  449. }
  450. /* Move asteroids. */
  451. void update_asteroids_position(AsteroidsApp* app) {
  452. for(int j = 0; j < app->asteroids_num; j++) {
  453. update_pos_by_velocity(
  454. &app->asteroids[j].x, &app->asteroids[j].y, app->asteroids[j].vx, app->asteroids[j].vy);
  455. app->asteroids[j].rot += app->asteroids[j].rot_speed;
  456. if(app->asteroids[j].rot < 0)
  457. app->asteroids[j].rot = 2 * PI;
  458. else if(app->asteroids[j].rot > 2 * PI)
  459. app->asteroids[j].rot = 0;
  460. }
  461. }
  462. /* Collision detection and game state update based on collisions. */
  463. void detect_collisions(AsteroidsApp* app) {
  464. /* Detect collision between bullet and asteroid. */
  465. for(int j = 0; j < app->bullets_num; j++) {
  466. Bullet* b = &app->bullets[j];
  467. for(int i = 0; i < app->asteroids_num; i++) {
  468. Asteroid* a = &app->asteroids[i];
  469. if(objects_are_colliding(a->x, a->y, a->size, b->x, b->y, 1.5, 1)) {
  470. asteroid_was_hit(app, i);
  471. remove_bullet(app, j);
  472. /* The bullet no longer exist. Break the loop.
  473. * However we want to start processing from the
  474. * same bullet index, since now it is used by
  475. * another bullet (see remove_bullet()). */
  476. j--; /* Scan this j value again. */
  477. break;
  478. }
  479. }
  480. }
  481. /* Detect collision between ship and asteroid. */
  482. for(int j = 0; j < app->asteroids_num; j++) {
  483. Asteroid* a = &app->asteroids[j];
  484. if(objects_are_colliding(a->x, a->y, a->size, app->ship.x, app->ship.y, 4, 1)) {
  485. ship_was_hit(app);
  486. break;
  487. }
  488. }
  489. }
  490. /* This is the main game execution function, called 10 times for
  491. * second (with the Flipper screen latency, an higher FPS does not
  492. * make sense). In this function we update the position of objects based
  493. * on velocity. Detect collisions. Update the score and so forth.
  494. *
  495. * Each time this function is called, app->tick is incremented. */
  496. void game_tick(void* ctx) {
  497. AsteroidsApp* app = ctx;
  498. /* There are two special screens:
  499. *
  500. * 1. Ship was hit, we frozen the game as long as ship_hit isn't zero
  501. * again, and show an animation of a rotating ship. */
  502. if(app->ship_hit) {
  503. notification_message(furi_record_open(RECORD_NOTIFICATION), &sequence_crash);
  504. app->ship.rot += 0.5;
  505. app->ship_hit--;
  506. view_port_update(app->view_port);
  507. if(app->ship_hit == 0) {
  508. restart_game(app);
  509. }
  510. return;
  511. } else if(app->gameover) {
  512. /* 2. Game over. We need to update only background asteroids. In this
  513. * state the game just displays a GAME OVER text with the floating
  514. * asteroids in backgroud. */
  515. if(key_pressed_time(app, InputKeyOk) > 100) {
  516. restart_game_after_gameover(app);
  517. }
  518. update_asteroids_position(app);
  519. view_port_update(app->view_port);
  520. return;
  521. }
  522. /* Handle keypresses. */
  523. if(app->pressed[InputKeyLeft]) app->ship.rot -= .35;
  524. if(app->pressed[InputKeyRight]) app->ship.rot += .35;
  525. if(app->pressed[InputKeyUp]) {
  526. app->ship.vx -= 0.5 * (float)sin(app->ship.rot);
  527. app->ship.vy += 0.5 * (float)cos(app->ship.rot);
  528. } else if(app->pressed[InputKeyDown]) {
  529. app->ship.vx *= 0.75;
  530. app->ship.vy *= 0.75;
  531. }
  532. /* Fire a bullet if needed. app->fire is set in
  533. * asteroids_update_keypress_state() since depends on exact
  534. * pressure timing. */
  535. if(app->fire) {
  536. uint32_t bullet_min_period = 200; // In milliseconds
  537. uint32_t now = furi_get_tick();
  538. if(now - app->last_bullet_tick >= bullet_min_period) {
  539. ship_fire_bullet(app);
  540. app->last_bullet_tick = now;
  541. }
  542. app->fire = false;
  543. }
  544. /* Update positions and detect collisions. */
  545. update_pos_by_velocity(&app->ship.x, &app->ship.y, app->ship.vx, app->ship.vy);
  546. update_bullets_position(app);
  547. update_asteroids_position(app);
  548. detect_collisions(app);
  549. /* From time to time, create a new asteroid. The more asteroids
  550. * already on the screen, the smaller probability of creating
  551. * a new one. */
  552. if(app->asteroids_num == 0 || (random() % 5000) < (30 / (1 + app->asteroids_num))) {
  553. add_asteroid(app);
  554. }
  555. app->ticks++;
  556. view_port_update(app->view_port);
  557. }
  558. /* ======================== Flipper specific code =========================== */
  559. bool load_game(AsteroidsApp* app) {
  560. Storage* storage = furi_record_open(RECORD_STORAGE);
  561. File* file = storage_file_alloc(storage);
  562. uint16_t bytes_readed = 0;
  563. if(storage_file_open(file, SAVING_FILENAME, FSAM_READ, FSOM_OPEN_EXISTING)) {
  564. bytes_readed = storage_file_read(file, app, sizeof(AsteroidsApp));
  565. }
  566. storage_file_close(file);
  567. storage_file_free(file);
  568. furi_record_close(RECORD_STORAGE);
  569. return bytes_readed == sizeof(AsteroidsApp);
  570. }
  571. void save_game(AsteroidsApp* app) {
  572. Storage* storage = furi_record_open(RECORD_STORAGE);
  573. if(storage_common_stat(storage, SAVING_DIRECTORY, NULL) == FSE_NOT_EXIST) {
  574. if(!storage_simply_mkdir(storage, SAVING_DIRECTORY)) {
  575. return;
  576. }
  577. }
  578. File* file = storage_file_alloc(storage);
  579. if(storage_file_open(file, SAVING_FILENAME, FSAM_WRITE, FSOM_CREATE_ALWAYS)) {
  580. storage_file_write(file, app, sizeof(AsteroidsApp));
  581. }
  582. storage_file_close(file);
  583. storage_file_free(file);
  584. furi_record_close(RECORD_STORAGE);
  585. }
  586. /* Here all we do is putting the events into the queue that will be handled
  587. * in the while() loop of the app entry point function. */
  588. void input_callback(InputEvent* input_event, void* ctx) {
  589. AsteroidsApp* app = ctx;
  590. furi_message_queue_put(app->event_queue, input_event, FuriWaitForever);
  591. }
  592. /* Allocate the application state and initialize a number of stuff.
  593. * This is called in the entry point to create the application state. */
  594. AsteroidsApp* asteroids_app_alloc() {
  595. AsteroidsApp* app = malloc(sizeof(AsteroidsApp));
  596. load_game(app);
  597. app->gui = furi_record_open(RECORD_GUI);
  598. app->view_port = view_port_alloc();
  599. view_port_draw_callback_set(app->view_port, render_callback, app);
  600. view_port_input_callback_set(app->view_port, input_callback, app);
  601. gui_add_view_port(app->gui, app->view_port, GuiLayerFullscreen);
  602. app->event_queue = furi_message_queue_alloc(8, sizeof(InputEvent));
  603. app->running = 1; /* Turns 0 when back is pressed. */
  604. restart_game_after_gameover(app);
  605. memset(app->pressed, 0, sizeof(app->pressed));
  606. return app;
  607. }
  608. /* Free what the application allocated. It is not clear to me if the
  609. * Flipper OS, once the application exits, will be able to reclaim space
  610. * even if we forget to free something here. */
  611. void asteroids_app_free(AsteroidsApp* app) {
  612. furi_assert(app);
  613. // View related.
  614. view_port_enabled_set(app->view_port, false);
  615. gui_remove_view_port(app->gui, app->view_port);
  616. view_port_free(app->view_port);
  617. furi_record_close(RECORD_GUI);
  618. furi_message_queue_free(app->event_queue);
  619. app->gui = NULL;
  620. free(app);
  621. }
  622. /* Return the time in milliseconds the specified key is continuously
  623. * pressed. Or 0 if it is not pressed. */
  624. uint32_t key_pressed_time(AsteroidsApp* app, InputKey key) {
  625. return app->pressed[key] == 0 ? 0 : furi_get_tick() - app->pressed[key];
  626. }
  627. /* Handle keys interaction. */
  628. void asteroids_update_keypress_state(AsteroidsApp* app, InputEvent input) {
  629. // Allow Rapid fire
  630. if(input.key == InputKeyOk) {
  631. app->fire = true;
  632. }
  633. if(input.type == InputTypePress) {
  634. app->pressed[input.key] = furi_get_tick();
  635. } else if(input.type == InputTypeRelease) {
  636. app->pressed[input.key] = 0;
  637. }
  638. }
  639. int32_t asteroids_app_entry(void* p) {
  640. UNUSED(p);
  641. AsteroidsApp* app = asteroids_app_alloc();
  642. /* Create a timer. We do data analysis in the callback. */
  643. FuriTimer* timer = furi_timer_alloc(game_tick, FuriTimerTypePeriodic, app);
  644. furi_timer_start(timer, furi_kernel_get_tick_frequency() / 10);
  645. /* This is the main event loop: here we get the events that are pushed
  646. * in the queue by input_callback(), and process them one after the
  647. * other. */
  648. InputEvent input;
  649. while(app->running) {
  650. FuriStatus qstat = furi_message_queue_get(app->event_queue, &input, 100);
  651. if(qstat == FuriStatusOk) {
  652. if(DEBUG_MSG)
  653. FURI_LOG_E(TAG, "Main Loop - Input: type %d key %u", input.type, input.key);
  654. /* Handle navigation here. Then handle view-specific inputs
  655. * in the view specific handling function. */
  656. if(input.type == InputTypeShort && input.key == InputKeyBack) {
  657. app->running = 0;
  658. } else {
  659. asteroids_update_keypress_state(app, input);
  660. }
  661. } else {
  662. /* Useful to understand if the app is still alive when it
  663. * does not respond because of bugs. */
  664. if(DEBUG_MSG) {
  665. static int c = 0;
  666. c++;
  667. if(!(c % 20)) FURI_LOG_E(TAG, "Loop timeout");
  668. }
  669. }
  670. }
  671. furi_timer_free(timer);
  672. asteroids_app_free(app);
  673. return 0;
  674. }