app.c 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174
  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. #include <asteroids_icons.h>
  16. #define TAG "Asteroids" // Used for logging
  17. #define DEBUG_MSG 1
  18. #define SCREEN_XRES 128
  19. #define SCREEN_YRES 64
  20. #define GAME_START_LIVES 3
  21. #define MAXLIVES 8 /* Max lives allowed. */
  22. #define TTLBUL 30 /* Bullet time to live, in ticks. */
  23. #define MAXBUL 50 /* Max bullets on the screen. */
  24. //@todo MAX Asteroids
  25. #define MAXAST 32 /* Max asteroids on the screen. */
  26. #define MAXPOWERUPS 3 /* Max powerups allowed on screen */
  27. #define POWERUPSTTL 400 /* Max powerup time to live, in ticks. */
  28. #define SHIP_HIT_ANIMATION_LEN 15
  29. #define SAVING_DIRECTORY "/ext/apps/Games"
  30. #define SAVING_FILENAME SAVING_DIRECTORY "/game_asteroids.save"
  31. #ifndef PI
  32. #define PI 3.14159265358979f
  33. #endif
  34. /* ============================ Data structures ============================= */
  35. typedef enum PowerUpType {
  36. PowerUpTypeShield, // Shield
  37. PowerUpTypeLife, // Extra life
  38. PowerUpTypeFirePower, // Burst Fire power
  39. PowerUpTypeRadialFire, // Radial Fire power
  40. PowerUpTypeNuke, // Nuke power
  41. PowerUpTypeClone, // Clone ship
  42. PowerUpTypeAssist, // Secondary ship
  43. Number_of_PowerUps // Used to count the number of powerups
  44. } PowerUpType;
  45. // struct PowerUp
  46. typedef struct PowerUp {
  47. float x, y, vx, vy; /* Fields like in ship. */
  48. // rot, /* Fields like ship. */
  49. // rot_speed, /* Angular velocity (rot speed and sense). */
  50. int size; /* Power Up size */
  51. uint32_t ttl; /* Time to live, in ticks. */
  52. uint32_t display_ttl; /* How long to display the powerup before it disappears */
  53. enum PowerUpType powerUpType; /* PowerUp type */
  54. bool isPowerUpActive; /* Is the powerup active? */
  55. } PowerUp;
  56. typedef struct Ship {
  57. float x, /* Ship x position. */
  58. y, /* Ship y position. */
  59. vx, /* x velocity. */
  60. vy, /* y velocity. */
  61. rot; /* Current rotation. 2*PI full ortation. */
  62. } Ship;
  63. typedef struct Bullet {
  64. float x, y, vx, vy; /* Fields like in ship. */
  65. uint32_t ttl; /* Time to live, in ticks. */
  66. } Bullet;
  67. typedef struct Asteroid {
  68. float x, y, vx, vy, rot, /* Fields like ship. */
  69. rot_speed, /* Angular velocity (rot speed and sense). */
  70. size; /* Asteroid size. */
  71. uint8_t shape_seed; /* Seed to give random shape. */
  72. } Asteroid;
  73. // @todo AsteroidsApp
  74. typedef struct AsteroidsApp {
  75. /* GUI */
  76. Gui* gui;
  77. ViewPort* view_port; /* We just use a raw viewport and we render
  78. everything into the low level canvas. */
  79. FuriMessageQueue* event_queue; /* Keypress events go here. */
  80. /* Game state. */
  81. int running; /* Once false exists the app. */
  82. bool gameover; /* Gameover status. */
  83. uint32_t ticks; /* Game ticks. Increments at each refresh. */
  84. uint32_t score; /* Game score. */
  85. uint32_t highscore; /* Highscore. Shown on Game Over Screen */
  86. bool is_new_highscore; /* Is the last score a new highscore? */
  87. uint32_t lives; /* Number of lives in the current game. */
  88. uint32_t ship_hit; /* When non zero, the ship was hit by an asteroid
  89. and we need to show an animation as long as
  90. its value is non-zero (and decrease it's value
  91. at each tick of animation). */
  92. /* Ship state. */
  93. struct Ship ship;
  94. struct PowerUp powerUps[MAXPOWERUPS]; /* Each powerup state. */
  95. int powerUps_num; /* Active powerups. */
  96. /* Bullets state. */
  97. struct Bullet bullets[MAXBUL]; /* Each bullet state. */
  98. int bullets_num; /* Active bullets. */
  99. uint32_t last_bullet_tick; /* Tick the last bullet was fired. */
  100. uint32_t bullet_min_period; /* Minimum time between bullets in ms. */
  101. /* Asteroids state. */
  102. Asteroid asteroids[MAXAST]; /* Each asteroid state. */
  103. int asteroids_num; /* Active asteroids. */
  104. uint32_t pressed[InputKeyMAX]; /* pressed[id] is true if pressed.
  105. Each array item contains the time
  106. in milliseconds the key was pressed. */
  107. bool fire; /* Short press detected: fire a bullet. */
  108. } AsteroidsApp;
  109. const NotificationSequence sequence_thrusters = {
  110. &message_vibro_on,
  111. &message_delay_10,
  112. &message_vibro_off,
  113. NULL,
  114. };
  115. const NotificationSequence sequence_brake = {
  116. &message_vibro_on,
  117. &message_delay_10,
  118. &message_delay_1,
  119. &message_delay_1,
  120. &message_vibro_off,
  121. NULL,
  122. };
  123. const NotificationSequence sequence_crash = {
  124. &message_red_255,
  125. &message_vibro_on,
  126. // &message_note_g5, // Play sound but currently disabled
  127. &message_delay_25,
  128. // &message_note_e5,
  129. &message_vibro_off,
  130. &message_sound_off,
  131. NULL,
  132. };
  133. const NotificationSequence sequence_bullet_fired = {
  134. &message_vibro_on,
  135. // &message_note_g5, // Play sound but currently disabled. Need On/Off menu setting
  136. &message_delay_10,
  137. &message_delay_1,
  138. &message_delay_1,
  139. &message_delay_1,
  140. &message_delay_1,
  141. &message_delay_1,
  142. // &message_note_e5,
  143. &message_vibro_off,
  144. &message_sound_off,
  145. NULL,
  146. };
  147. const NotificationSequence sequence_nuke = {
  148. &message_red_255,
  149. &message_vibro_on,
  150. // &message_note_g5, // Play sound but currently disabled
  151. &message_delay_250,
  152. &message_red_0,
  153. &message_vibro_off,
  154. &message_red_255,
  155. &message_vibro_on,
  156. // &message_note_g5, // Play sound but currently disabled
  157. &message_delay_250,
  158. &message_red_0,
  159. &message_vibro_off,
  160. &message_vibro_on,
  161. &message_red_255,
  162. &message_delay_100,
  163. &message_red_0,
  164. &message_vibro_off,
  165. &message_delay_1,
  166. &message_delay_1,
  167. &message_vibro_on,
  168. &message_red_255,
  169. &message_delay_100,
  170. &message_red_0,
  171. &message_vibro_off,
  172. &message_delay_1,
  173. &message_delay_1,
  174. &message_delay_1,
  175. &message_vibro_on,
  176. &message_red_255,
  177. &message_delay_100,
  178. &message_red_0,
  179. &message_vibro_off,
  180. &message_delay_1,
  181. &message_delay_1,
  182. &message_delay_1,
  183. &message_vibro_on,
  184. &message_delay_1,
  185. &message_delay_1,
  186. &message_delay_1,
  187. &message_delay_1,
  188. &message_delay_1,
  189. &message_red_0,
  190. &message_vibro_off,
  191. &message_delay_1,
  192. &message_delay_1,
  193. &message_vibro_on,
  194. &message_delay_1,
  195. &message_delay_1,
  196. &message_delay_1,
  197. &message_red_0,
  198. &message_vibro_off,
  199. &message_delay_1,
  200. &message_vibro_on,
  201. &message_delay_1,
  202. &message_delay_1,
  203. &message_red_0,
  204. &message_vibro_off,
  205. &message_sound_off,
  206. NULL,
  207. };
  208. /* ============================== Prototyeps ================================ */
  209. // Only functions called before their definition are here.
  210. bool isPowerUpActive(AsteroidsApp* app, enum PowerUpType powerUpType);
  211. bool isPowerUpAlreadyExists(AsteroidsApp* app, enum PowerUpType powerUpType);
  212. bool load_game(AsteroidsApp* app);
  213. void save_game(AsteroidsApp* app);
  214. void restart_game_after_gameover(AsteroidsApp* app);
  215. uint32_t key_pressed_time(AsteroidsApp* app, InputKey key);
  216. /* ============================ 2D drawing ================================== */
  217. /* This structure represents a polygon of at most POLY_MAX points.
  218. * The function draw_poly() is able to render it on the screen, rotated
  219. * by the amount specified. */
  220. #define POLY_MAX 8
  221. typedef struct Poly {
  222. float x[POLY_MAX];
  223. float y[POLY_MAX];
  224. uint32_t points; /* Number of points actually populated. */
  225. } Poly;
  226. /* Define the polygons we use. */
  227. Poly ShipPoly = {{-3, 0, 3}, {-3, 6, -3}, 3};
  228. Poly ShipFirePoly = {{-1.5, 0, 1.5}, {-3, -6, -3}, 3};
  229. /* Rotate the point of the poligon 'poly' and store the new rotated
  230. * polygon in 'rot'. The polygon is rotated by an angle 'a', with
  231. * center at 0,0. */
  232. void rotate_poly(Poly* rot, Poly* poly, float a) {
  233. /* We want to compute sin(a) and cos(a) only one time
  234. * for every point to rotate. It's a slow operation. */
  235. float sin_a = (float)sin(a);
  236. float cos_a = (float)cos(a);
  237. for(uint32_t j = 0; j < poly->points; j++) {
  238. rot->x[j] = poly->x[j] * cos_a - poly->y[j] * sin_a;
  239. rot->y[j] = poly->y[j] * cos_a + poly->x[j] * sin_a;
  240. }
  241. rot->points = poly->points;
  242. }
  243. /* This is an 8 bit LFSR we use to generate a predictable and fast
  244. * pseudorandom sequence of numbers, to give a different shape to
  245. * each asteroid. */
  246. void lfsr_next(unsigned char* prev) {
  247. unsigned char lsb = *prev & 1;
  248. *prev = *prev >> 1;
  249. if(lsb == 1) *prev ^= 0b11000111;
  250. *prev ^= *prev << 7; /* Mix things a bit more. */
  251. }
  252. /* Render the polygon 'poly' at x,y, rotated by the specified angle. */
  253. void draw_poly(Canvas* const canvas, Poly* poly, uint8_t x, uint8_t y, float a) {
  254. Poly rot;
  255. rotate_poly(&rot, poly, a);
  256. canvas_set_color(canvas, ColorBlack);
  257. for(uint32_t j = 0; j < rot.points; j++) {
  258. uint32_t a = j;
  259. uint32_t b = j + 1;
  260. if(b == rot.points) b = 0;
  261. canvas_draw_line(canvas, x + rot.x[a], y + rot.y[a], x + rot.x[b], y + rot.y[b]);
  262. }
  263. }
  264. /* A bullet is just a + pixels pattern. A single pixel is not
  265. * visible enough. */
  266. void draw_bullet(Canvas* const canvas, Bullet* b) {
  267. canvas_draw_dot(canvas, b->x - 1, b->y);
  268. canvas_draw_dot(canvas, b->x + 1, b->y);
  269. canvas_draw_dot(canvas, b->x, b->y);
  270. canvas_draw_dot(canvas, b->x, b->y - 1);
  271. canvas_draw_dot(canvas, b->x, b->y + 1);
  272. }
  273. /* Draw an asteroid. The asteroid shapes is computed on the fly and
  274. * is not stored in a permanent shape structure. In order to generate
  275. * the shape, we use an initial fixed shape that we resize according
  276. * to the asteroid size, perturbate according to the asteroid shape
  277. * seed, and finally draw it rotated of the right amount. */
  278. void draw_asteroid(Canvas* const canvas, Asteroid* ast) {
  279. Poly ap;
  280. /* Start with what is kinda of a circle. Note that this could be
  281. * stored into a template and copied here, to avoid computing
  282. * sin() / cos(). But the Flipper can handle it without problems. */
  283. uint8_t r = ast->shape_seed;
  284. for(int j = 0; j < 8; j++) {
  285. float a = (PI * 2) / 8 * j;
  286. /* Before generating the point, to make the shape unique generate
  287. * a random factor between .7 and 1.3 to scale the distance from
  288. * the center. However this asteroid should have its unique shape
  289. * that remains always the same, so we use a predictable PRNG
  290. * implemented by an 8 bit shift register. */
  291. lfsr_next(&r);
  292. float scaling = .7 + ((float)r / 255 * .6);
  293. ap.x[j] = (float)sin(a) * ast->size * scaling;
  294. ap.y[j] = (float)cos(a) * ast->size * scaling;
  295. }
  296. ap.points = 8;
  297. draw_poly(canvas, &ap, ast->x, ast->y, ast->rot);
  298. }
  299. /* Draw small ships in the top-right part of the screen, one for
  300. * each left live. */
  301. void draw_left_lives(Canvas* const canvas, AsteroidsApp* app) {
  302. int lives = app->lives;
  303. int x = SCREEN_XRES - 5;
  304. Poly mini_ship = {{-2, 0, 2}, {-2, 4, -2}, 3};
  305. while(lives--) {
  306. draw_poly(canvas, &mini_ship, x, 6, PI);
  307. x -= 6;
  308. }
  309. }
  310. bool should_draw_powerUp(PowerUp* const p) {
  311. // Just return if power up has already been picked up
  312. if(p->display_ttl == 0) return false;
  313. // Begin flashing power up when it is about to expire
  314. if(p->display_ttl < 100) {
  315. return p->display_ttl % 8 > 0;
  316. }
  317. return true;
  318. }
  319. void draw_powerUps(Canvas* const canvas, PowerUp* const p) {
  320. /*
  321. * * * * * * * * * *
  322. * *
  323. * *
  324. * *
  325. * F *
  326. * *
  327. * *
  328. * *
  329. * *
  330. * * * * * * * * * *
  331. BOX_SIZE = 10
  332. Box_Width = BOX_SIZE
  333. BOX_HEIGHT = BOX_SIZE
  334. BOX_X_POS = x - BOX_WIDTH/2
  335. BOX_Y_POS = y - BOX_HEIGHT/2
  336. POS_F_X = WIDTH/2
  337. POS_F_Y = HEIGHT/2
  338. */
  339. //@todo render_callback
  340. // Just return if power up has already been picked up
  341. // FURI_LOG_I(TAG, "[draw_powerUps] Display TTL: %lu", p->display_ttl);
  342. if(p->display_ttl == 0) return;
  343. if(!should_draw_powerUp(p)) return;
  344. canvas_set_color(canvas, ColorXOR);
  345. // Display power up to be picked up
  346. switch(p->powerUpType) {
  347. case PowerUpTypeFirePower:
  348. canvas_draw_icon(canvas, p->x, p->y, &I_firepower_shifted_9x10);
  349. break;
  350. case PowerUpTypeShield:
  351. canvas_draw_icon(canvas, p->x, p->y, &I_shield_frame);
  352. break;
  353. case PowerUpTypeLife:
  354. // Draw a heart
  355. canvas_draw_icon(canvas, p->x, p->y, &I_heart_10x10);
  356. break;
  357. case PowerUpTypeNuke:
  358. // canvas_draw_disc(canvas, p->x, p->y, p->size);
  359. // canvas_draw_str(canvas, p->x, p->y, "N");
  360. canvas_draw_icon(canvas, p->x, p->y, &I_nuke_10x10);
  361. break;
  362. case PowerUpTypeRadialFire:
  363. // Draw box with letter R inside
  364. canvas_draw_str(canvas, p->x, p->y, "R");
  365. break;
  366. case PowerUpTypeAssist:
  367. // Draw box with letter A inside
  368. canvas_draw_str(canvas, p->x, p->y, "A");
  369. break;
  370. case PowerUpTypeClone:
  371. // Draw box with letter C inside
  372. canvas_draw_str(canvas, p->x, p->y, "C");
  373. break;
  374. default:
  375. //@todo Uknown Power Up Type Detected
  376. // Draw box with letter U inside
  377. canvas_draw_str(canvas, p->x, p->y, "?");
  378. FURI_LOG_E(TAG, "Unexpected Power Up Type Detected: %i", p->powerUpType);
  379. break;
  380. }
  381. }
  382. void draw_shield(Canvas* const canvas, AsteroidsApp* app) {
  383. if(isPowerUpActive(app, PowerUpTypeShield) == false) return;
  384. canvas_set_color(canvas, ColorXOR);
  385. // canvas_draw_disc(canvas, app->ship.x, app->ship.y, 4);
  386. canvas_draw_circle(canvas, app->ship.x, app->ship.y, 10);
  387. }
  388. /* Given the current position, update it according to the velocity and
  389. * wrap it back to the other side if the object went over the screen. */
  390. void update_pos_by_velocity(float* x, float* y, float vx, float vy) {
  391. /* Return back from one side to the other of the screen. */
  392. *x += vx;
  393. *y += vy;
  394. if(*x >= SCREEN_XRES)
  395. *x = 0;
  396. else if(*x < 0)
  397. *x = SCREEN_XRES - 1;
  398. if(*y >= SCREEN_YRES)
  399. *y = 0;
  400. else if(*y < 0)
  401. *y = SCREEN_YRES - 1;
  402. }
  403. /* Render the current game screen. */
  404. void render_callback(Canvas* const canvas, void* ctx) {
  405. AsteroidsApp* app = ctx;
  406. /* Clear screen. */
  407. canvas_set_color(canvas, ColorWhite);
  408. canvas_draw_box(canvas, 0, 0, SCREEN_XRES - 1, SCREEN_YRES - 1);
  409. /* Draw score. */
  410. canvas_set_color(canvas, ColorBlack);
  411. canvas_set_font(canvas, FontSecondary);
  412. char score[32];
  413. snprintf(score, sizeof(score), "%lu", app->score);
  414. canvas_draw_str(canvas, 0, 8, score);
  415. /* Draw left ships. */
  416. draw_left_lives(canvas, app);
  417. /* Draw ship, asteroids, bullets. */
  418. draw_poly(canvas, &ShipPoly, app->ship.x, app->ship.y, app->ship.rot);
  419. /* Draw shield if active. */
  420. draw_shield(canvas, app);
  421. if(key_pressed_time(app, InputKeyUp) > 0) {
  422. notification_message(furi_record_open(RECORD_NOTIFICATION), &sequence_thrusters);
  423. draw_poly(canvas, &ShipFirePoly, app->ship.x, app->ship.y, app->ship.rot);
  424. }
  425. for(int j = 0; j < app->bullets_num; j++) draw_bullet(canvas, &app->bullets[j]);
  426. for(int j = 0; j < app->asteroids_num; j++) draw_asteroid(canvas, &app->asteroids[j]);
  427. for(int j = 0; j < app->powerUps_num; j++) draw_powerUps(canvas, &app->powerUps[j]);
  428. /* Game over text. */
  429. if(app->gameover) {
  430. canvas_set_color(canvas, ColorBlack);
  431. canvas_set_font(canvas, FontPrimary);
  432. // TODO: if new highscore, display blinking "New High Score"
  433. // Display High Score
  434. if(app->is_new_highscore) {
  435. canvas_draw_str(canvas, 22, 9, "New High Score!");
  436. } else {
  437. canvas_draw_str(canvas, 36, 9, "High Score");
  438. }
  439. // Convert highscore to string
  440. int length = snprintf(NULL, 0, "%lu", app->highscore);
  441. char* str_high_score = malloc(length + 1);
  442. snprintf(str_high_score, length + 1, "%lu", app->highscore);
  443. // Get length to center on screen
  444. int nDigits = 0;
  445. if(app->highscore > 0) {
  446. nDigits = floor(log10(app->highscore)) + 1;
  447. }
  448. // Draw highscore centered
  449. canvas_draw_str(canvas, (SCREEN_XRES / 2) - (nDigits * 2), 20, str_high_score);
  450. free(str_high_score);
  451. canvas_draw_str(canvas, 28, 35, "GAME OVER");
  452. canvas_set_font(canvas, FontSecondary);
  453. canvas_draw_str(canvas, 25, 50, "Press OK to restart");
  454. }
  455. }
  456. /* ============================ Game logic ================================== */
  457. float distance(float x1, float y1, float x2, float y2) {
  458. float dx = x1 - x2;
  459. float dy = y1 - y2;
  460. return sqrt(dx * dx + dy * dy);
  461. }
  462. /* Detect a collision between the object at x1,y1 of radius r1 and
  463. * the object at x2, y2 of radius r2. A factor < 1 will make the
  464. * function detect the collision even if the objects are yet not
  465. * relly touching, while a factor > 1 will make it detect the collision
  466. * only after they are a bit overlapping. It basically is used to
  467. * rescale the distance.
  468. *
  469. * Note that in this simplified 2D world, objects are all considered
  470. * spheres (this is why this function only takes the radius). This
  471. * is, after all, kinda accurate for asteroids, for bullets, and
  472. * even for the ship "core" itself. */
  473. bool objects_are_colliding(float x1, float y1, float r1, float x2, float y2, float r2, float factor) {
  474. /* The objects are colliding if the distance between object 1 and 2
  475. * is smaller than the sum of the two radiuses r1 and r2.
  476. * So it would be like: sqrt((x1-x2)^2+(y1-y2)^2) < r1+r2.
  477. * However we can avoid computing the sqrt (which is slow) by
  478. * squaring the second term and removing the square root, making
  479. * the comparison like this:
  480. *
  481. * (x1-x2)^2+(y1-y2)^2 < (r1+r2)^2. */
  482. float dx = (x1 - x2) * factor;
  483. float dy = (y1 - y2) * factor;
  484. float rsum = r1 + r2;
  485. return dx * dx + dy * dy < rsum * rsum;
  486. }
  487. //@todo ship_fire_bullet
  488. /* Create a new bullet headed in the same direction of the ship. */
  489. void ship_fire_bullet(AsteroidsApp* app) {
  490. // No power ups, only 5 bullets allowed
  491. if(isPowerUpActive(app, PowerUpTypeFirePower) == false && app->bullets_num >= 5) return;
  492. // Double the Fire Power
  493. if(isPowerUpActive(app, PowerUpTypeFirePower) && (app->bullets_num >= (MAXBUL))) return;
  494. notification_message(furi_record_open(RECORD_NOTIFICATION), &sequence_bullet_fired);
  495. Bullet* b = &app->bullets[app->bullets_num];
  496. b->x = app->ship.x;
  497. b->y = app->ship.y;
  498. b->vx = -sin(app->ship.rot);
  499. b->vy = cos(app->ship.rot);
  500. /* Ship should fire from its head, not in the middle. */
  501. b->x += b->vx * 5;
  502. b->y += b->vy * 5;
  503. /* Give the bullet some velocity (for now the vector is just
  504. * normalized to 1). */
  505. b->vx *= 3;
  506. b->vy *= 3;
  507. /* It's more realistic if we add the velocity vector of the
  508. * ship, too. Otherwise if the ship is going fast the bullets
  509. * will be slower, which is not how the world works. */
  510. b->vx += app->ship.vx;
  511. b->vy += app->ship.vy;
  512. b->ttl = TTLBUL; /* The bullet will disappear after N ticks. */
  513. app->bullets_num++;
  514. }
  515. /* Remove the specified bullet by id (index in the array). */
  516. void remove_bullet(AsteroidsApp* app, int bid) {
  517. /* Replace the top bullet with the empty space left
  518. * by the removal of this bullet. This way we always take the
  519. * array dense, which is an advantage when looping. */
  520. int n = --app->bullets_num;
  521. if(n && bid != n) app->bullets[bid] = app->bullets[n];
  522. }
  523. /* Create a new asteroid, away from the ship. Return the
  524. * pointer to the asteroid object, so that the caller can change
  525. * certain things of the asteroid if needed. */
  526. Asteroid* add_asteroid(AsteroidsApp* app) {
  527. if(app->asteroids_num == MAXAST) return NULL;
  528. float size = 4 + rand() % 15;
  529. float min_distance = 20;
  530. float x, y;
  531. do {
  532. x = rand() % SCREEN_XRES;
  533. y = rand() % SCREEN_YRES;
  534. } while(distance(app->ship.x, app->ship.y, x, y) < min_distance + size);
  535. Asteroid* a = &app->asteroids[app->asteroids_num++];
  536. a->x = x;
  537. a->y = y;
  538. a->vx = 2 * (-.5 + ((float)rand() / RAND_MAX));
  539. a->vy = 2 * (-.5 + ((float)rand() / RAND_MAX));
  540. a->size = size;
  541. a->rot = 0;
  542. a->rot_speed = ((float)rand() / RAND_MAX) / 10;
  543. if(app->ticks & 1) a->rot_speed = -(a->rot_speed);
  544. a->shape_seed = rand() & 255;
  545. return a;
  546. }
  547. /* Remove the specified asteroid by id (index in the array). */
  548. void remove_asteroid(AsteroidsApp* app, int id) {
  549. /* Replace the top asteroid with the empty space left
  550. * by the removal of this one. This way we always take the
  551. * array dense, which is an advantage when looping. */
  552. int n = --app->asteroids_num;
  553. if(n && id != n) app->asteroids[id] = app->asteroids[n];
  554. }
  555. /* Called when an asteroid was reached by a bullet. The asteroid
  556. * hit is the one with the specified 'id'. */
  557. void asteroid_was_hit(AsteroidsApp* app, int id) {
  558. float sizelimit = 6; // Smaller than that polverize in one shot.
  559. Asteroid* a = &app->asteroids[id];
  560. /* Asteroid is large enough to break into fragments. */
  561. float size = a->size;
  562. float x = a->x, y = a->y;
  563. remove_asteroid(app, id);
  564. if(size > sizelimit) {
  565. int max_fragments = size / sizelimit;
  566. int fragments = 2 + rand() % max_fragments;
  567. float newsize = size / fragments;
  568. if(newsize < 2) newsize = 2;
  569. for(int j = 0; j < fragments; j++) {
  570. a = add_asteroid(app);
  571. if(a == NULL) break; // Too many asteroids on screen.
  572. a->x = x + -(size / 2) + rand() % (int)newsize;
  573. a->y = y + -(size / 2) + rand() % (int)newsize;
  574. a->size = newsize;
  575. }
  576. } else {
  577. app->score++;
  578. if(app->score > app->highscore) {
  579. app->is_new_highscore = true;
  580. app->highscore = app->score; // Show on Game Over Screen and future main menu
  581. }
  582. }
  583. }
  584. //@todo Add PowerUp
  585. PowerUp* add_powerUp(AsteroidsApp* app) {
  586. if(app->powerUps_num == MAXPOWERUPS) return NULL;
  587. // Randomly select power up for display
  588. //@todo Random Power Up Select
  589. PowerUpType selected_powerUpType = rand() % Number_of_PowerUps;
  590. // PowerUpType selected_powerUpType = PowerUpTypeFirePower;
  591. // PowerUpType selected_powerUpType = PowerUpTypeLife;
  592. // PowerUpType selected_powerUpType = PowerUpTypeNuke;
  593. // PowerUpType selected_powerUpType = PowerUpTypeShield;
  594. FURI_LOG_I(TAG, "[add_powerUp] Power Ups Active: %i", app->powerUps_num);
  595. // Don't add already existing power ups
  596. if(isPowerUpAlreadyExists(app, selected_powerUpType)) {
  597. FURI_LOG_I(TAG, "[add_powerUp] Power Up %i already active", selected_powerUpType);
  598. return NULL;
  599. }
  600. float size = 10;
  601. float min_distance = 20;
  602. float x, y;
  603. do {
  604. //size*2 to make sure power up is not spawned on the edge of the screen
  605. //It also keeps it away from the lives and score at the top of screen
  606. x = rand() % (SCREEN_XRES - (int)size);
  607. y = rand() % (SCREEN_YRES - (int)size);
  608. } while(distance(app->ship.x, app->ship.y, (float)x, (float)y) < min_distance + size);
  609. PowerUp* p = &app->powerUps[app->powerUps_num++];
  610. p->x = x;
  611. p->y = y;
  612. //@todo Disable Velocity
  613. p->vx = 0; //2 * (-.5 + ((float)rand() / RAND_MAX));
  614. p->vy = 0; //2 * (-.5 + ((float)rand() / RAND_MAX));
  615. p->display_ttl = 200;
  616. p->ttl = POWERUPSTTL;
  617. p->size = (int)size;
  618. // p->size = size;
  619. // p->rot = 0;
  620. // p->rot_speed = ((float)rand() / RAND_MAX) / 10;
  621. // if(app->ticks & 1) p->rot_speed = -(p->rot_speed);
  622. //@todo add powerup type, for now hardcoding to firepower
  623. p->powerUpType = selected_powerUpType;
  624. p->isPowerUpActive = false;
  625. return p;
  626. }
  627. //@todo remove_powerUp
  628. void remove_powerUp(AsteroidsApp* app, int id) {
  629. // Invalid ID, ignore
  630. if(id <= 0) return;
  631. // TODO: Break this out into object types that set the game state
  632. if(app->powerUps[id].powerUpType == PowerUpTypeFirePower) {
  633. app->bullet_min_period = 200;
  634. }
  635. /* Replace the top powerUp with the empty space left
  636. * by the removal of this one. This way we always take the
  637. * array dense, which is an advantage when looping. */
  638. int n = --app->powerUps_num;
  639. if(n && id != n) app->powerUps[id] = app->powerUps[n];
  640. }
  641. void remove_all_astroids_and_bullets(AsteroidsApp* app) {
  642. app->score += app->asteroids_num;
  643. app->asteroids_num = 0;
  644. app->bullets_num = 0;
  645. }
  646. //@todo powerUp_was_hit
  647. void powerUp_was_hit(AsteroidsApp* app, int id) {
  648. PowerUp* p = &app->powerUps[id];
  649. if(p->display_ttl == 0) return; // Don't collect if already collected
  650. switch(p->powerUpType) {
  651. case PowerUpTypeLife:
  652. if(app->lives < MAXLIVES) app->lives++;
  653. remove_powerUp(app, id);
  654. break;
  655. case PowerUpTypeFirePower:
  656. p->ttl = POWERUPSTTL / 2;
  657. app->bullet_min_period = 100;
  658. break;
  659. case PowerUpTypeNuke:
  660. //TODO: Animate explosion
  661. notification_message(furi_record_open(RECORD_NOTIFICATION), &sequence_nuke);
  662. remove_all_astroids_and_bullets(app);
  663. break;
  664. default:
  665. break;
  666. }
  667. p->display_ttl = 0;
  668. p->isPowerUpActive = true;
  669. }
  670. bool isPowerUpActive(AsteroidsApp* const app, PowerUpType const powerUpType) {
  671. for(int i = 0; i < app->powerUps_num; i++) {
  672. // PowerUp* p = &app->powerUps[i];
  673. // if(p->powerUpType == powerUpType && p->ttl > 0 && p->display_ttl == 0) return true;
  674. if(app->powerUps[i].isPowerUpActive && app->powerUps[i].powerUpType == powerUpType) {
  675. return true;
  676. }
  677. }
  678. return false;
  679. }
  680. bool isPowerUpAlreadyExists(AsteroidsApp* const app, PowerUpType const powerUpType) {
  681. for(int i = 0; i < app->powerUps_num; i++) {
  682. if(app->powerUps[i].powerUpType == powerUpType) return true;
  683. }
  684. return false;
  685. }
  686. /* Set gameover state. When in game-over mode, the game displays a gameover
  687. * text with a background of many asteroids floating around. */
  688. void game_over(AsteroidsApp* app) {
  689. if(app->is_new_highscore) save_game(app); // Save highscore but only on change
  690. app->gameover = true;
  691. app->lives = GAME_START_LIVES; // Show 3 lives in game over screen to match new game start
  692. }
  693. /* Function called when a collision between the asteroid and the
  694. * ship is detected. */
  695. void ship_was_hit(AsteroidsApp* app) {
  696. app->ship_hit = SHIP_HIT_ANIMATION_LEN;
  697. if(app->lives) {
  698. app->lives--;
  699. } else {
  700. game_over(app);
  701. }
  702. }
  703. /* Restart game after the ship is hit. Will reset the ship position, bullets
  704. * and asteroids to restart the game. */
  705. void restart_game(AsteroidsApp* app) {
  706. app->ship.x = SCREEN_XRES / 2;
  707. app->ship.y = SCREEN_YRES / 2;
  708. app->ship.rot = PI; /* Start headed towards top. */
  709. app->ship.vx = 0;
  710. app->ship.vy = 0;
  711. app->bullets_num = 0;
  712. app->powerUps_num = 0;
  713. app->last_bullet_tick = 0;
  714. app->bullet_min_period = 200;
  715. app->asteroids_num = 0;
  716. app->ship_hit = 0;
  717. }
  718. /* Called after gameover to restart the game. This function
  719. * also calls restart_game(). */
  720. void restart_game_after_gameover(AsteroidsApp* app) {
  721. app->gameover = false;
  722. app->ticks = 0;
  723. app->score = 0;
  724. app->is_new_highscore = false;
  725. app->lives = GAME_START_LIVES - 1;
  726. restart_game(app);
  727. }
  728. /* Move bullets. */
  729. void update_bullets_position(AsteroidsApp* app) {
  730. for(int j = 0; j < app->bullets_num; j++) {
  731. update_pos_by_velocity(
  732. &app->bullets[j].x, &app->bullets[j].y, app->bullets[j].vx, app->bullets[j].vy);
  733. if(--app->bullets[j].ttl == 0) {
  734. remove_bullet(app, j);
  735. j--; /* Process this bullet index again: the removal will
  736. fill it with the top bullet to take the array dense. */
  737. }
  738. }
  739. }
  740. /* Move asteroids. */
  741. void update_asteroids_position(AsteroidsApp* app) {
  742. for(int j = 0; j < app->asteroids_num; j++) {
  743. update_pos_by_velocity(
  744. &app->asteroids[j].x, &app->asteroids[j].y, app->asteroids[j].vx, app->asteroids[j].vy);
  745. app->asteroids[j].rot += app->asteroids[j].rot_speed;
  746. if(app->asteroids[j].rot < 0)
  747. app->asteroids[j].rot = 2 * PI;
  748. else if(app->asteroids[j].rot > 2 * PI)
  749. app->asteroids[j].rot = 0;
  750. }
  751. }
  752. void update_powerUps_position(AsteroidsApp* app) {
  753. for(int j = 0; j < app->powerUps_num; j++) {
  754. // @todo update_powerUps_position
  755. if(app->powerUps[j].display_ttl > 0) {
  756. update_pos_by_velocity(
  757. &app->powerUps[j].x, &app->powerUps[j].y, app->powerUps[j].vx, app->powerUps[j].vy);
  758. }
  759. }
  760. }
  761. // @todo update_powerUp_status
  762. /* This updates the state of each power up collected and removes them if they have expired. */
  763. void update_powerUp_status(AsteroidsApp* app) {
  764. for(int j = app->powerUps_num; j > 0; j--) {
  765. if(app->powerUps[j].ttl > 0 && app->powerUps[j].isPowerUpActive) {
  766. // Only decrement ttl if we actually picked up power up
  767. app->powerUps[j].ttl--;
  768. } else if(app->powerUps[j].ttl == 0 && app->powerUps[j].display_ttl == 0) {
  769. // we've reached the end of life of the power up
  770. // Time to remove it
  771. app->powerUps[j].isPowerUpActive = false;
  772. remove_powerUp(app, j);
  773. } else if(app->powerUps[j].display_ttl > 0) {
  774. app->powerUps[j].display_ttl--;
  775. }
  776. }
  777. }
  778. /* Collision detection and game state update based on collisions. */
  779. void detect_collisions(AsteroidsApp* app) {
  780. /* Detect collision between bullet and asteroid. */
  781. for(int j = 0; j < app->bullets_num; j++) {
  782. Bullet* b = &app->bullets[j];
  783. for(int i = 0; i < app->asteroids_num; i++) {
  784. Asteroid* a = &app->asteroids[i];
  785. if(objects_are_colliding(a->x, a->y, a->size, b->x, b->y, 1.5, 1)) {
  786. asteroid_was_hit(app, i);
  787. remove_bullet(app, j);
  788. /* The bullet no longer exist. Break the loop.
  789. * However we want to start processing from the
  790. * same bullet index, since now it is used by
  791. * another bullet (see remove_bullet()). */
  792. j--; /* Scan this j value again. */
  793. break;
  794. }
  795. }
  796. }
  797. /* Detect collision between ship and asteroid. */
  798. for(int j = 0; j < app->asteroids_num; j++) {
  799. Asteroid* a = &app->asteroids[j];
  800. if(objects_are_colliding(a->x, a->y, a->size, app->ship.x, app->ship.y, 4, 1)) {
  801. if(isPowerUpActive(app, PowerUpTypeShield)) {
  802. // Asteroid was hit with shield
  803. notification_message(
  804. furi_record_open(RECORD_NOTIFICATION), &sequence_bullet_fired);
  805. asteroid_was_hit(app, j);
  806. } else {
  807. // No sheild active, take damage
  808. ship_was_hit(app);
  809. }
  810. break;
  811. }
  812. }
  813. /* Detect collision between ship and powerUp. */
  814. for(int j = 0; j < app->powerUps_num; j++) {
  815. PowerUp* p = &app->powerUps[j];
  816. if(objects_are_colliding(p->x, p->y, p->size, app->ship.x, app->ship.y, 4, 1)) {
  817. powerUp_was_hit(app, j);
  818. break;
  819. }
  820. }
  821. }
  822. /* This is the main game execution function, called 10 times for
  823. * second (with the Flipper screen latency, an higher FPS does not
  824. * make sense). In this function we update the position of objects based
  825. * on velocity. Detect collisions. Update the score and so forth.
  826. *
  827. * Each time this function is called, app->tick is incremented. */
  828. void game_tick(void* ctx) {
  829. AsteroidsApp* app = ctx;
  830. /* There are two special screens:
  831. *
  832. * 1. Ship was hit, we frozen the game as long as ship_hit isn't zero
  833. * again, and show an animation of a rotating ship. */
  834. if(app->ship_hit) {
  835. notification_message(furi_record_open(RECORD_NOTIFICATION), &sequence_crash);
  836. app->ship.rot += 0.5;
  837. app->ship_hit--;
  838. view_port_update(app->view_port);
  839. if(app->ship_hit == 0) {
  840. restart_game(app);
  841. }
  842. return;
  843. } else if(app->gameover) {
  844. /* 2. Game over. We need to update only background asteroids. In this
  845. * state the game just displays a GAME OVER text with the floating
  846. * asteroids in backgroud. */
  847. if(key_pressed_time(app, InputKeyOk) > 100) {
  848. restart_game_after_gameover(app);
  849. }
  850. update_asteroids_position(app);
  851. view_port_update(app->view_port);
  852. return;
  853. }
  854. /* Handle keypresses. */
  855. if(app->pressed[InputKeyLeft]) app->ship.rot -= .35;
  856. if(app->pressed[InputKeyRight]) app->ship.rot += .35;
  857. if(app->pressed[InputKeyUp]) {
  858. app->ship.vx -= 0.5 * (float)sin(app->ship.rot);
  859. app->ship.vy += 0.5 * (float)cos(app->ship.rot);
  860. } else if(app->pressed[InputKeyDown]) {
  861. notification_message(furi_record_open(RECORD_NOTIFICATION), &sequence_brake);
  862. app->ship.vx *= 0.75;
  863. app->ship.vy *= 0.75;
  864. }
  865. /* Fire a bullet if needed. app->fire is set in
  866. * asteroids_update_keypress_state() since depends on exact
  867. * pressure timing. */
  868. if(app->fire) {
  869. uint32_t now = furi_get_tick();
  870. if(now - app->last_bullet_tick >= app->bullet_min_period) {
  871. ship_fire_bullet(app);
  872. app->last_bullet_tick = now;
  873. }
  874. app->fire = false;
  875. }
  876. // DEBUG: Show Power Up Status
  877. for(int j = 0; j < app->powerUps_num; j++) {
  878. PowerUp* p = &app->powerUps[j];
  879. FURI_LOG_I(
  880. TAG,
  881. "Power Up Type: %d TTL: %lu Display_TTL: %lu PowerUpNum: %i",
  882. p->powerUpType,
  883. p->ttl,
  884. p->display_ttl,
  885. app->powerUps_num);
  886. }
  887. /* Update positions and detect collisions. */
  888. update_pos_by_velocity(&app->ship.x, &app->ship.y, app->ship.vx, app->ship.vy);
  889. update_bullets_position(app);
  890. update_asteroids_position(app);
  891. update_powerUp_status(app); //@todo update_powerUp_status
  892. update_powerUps_position(app);
  893. detect_collisions(app);
  894. /* From time to time, create a new asteroid. The more asteroids
  895. * already on the screen, the smaller probability of creating
  896. * a new one. */
  897. if(app->asteroids_num == 0 || (random() % 5000) < (30 / (1 + app->asteroids_num))) {
  898. add_asteroid(app);
  899. }
  900. /* From time to time add a random power up */
  901. //@todo game tick
  902. if((app->powerUps_num == 0 || random() % 5000) < (30 / (1 + app->powerUps_num))) {
  903. add_powerUp(app);
  904. }
  905. app->ticks++;
  906. view_port_update(app->view_port);
  907. }
  908. /* ======================== Flipper specific code =========================== */
  909. bool load_game(AsteroidsApp* app) {
  910. Storage* storage = furi_record_open(RECORD_STORAGE);
  911. File* file = storage_file_alloc(storage);
  912. uint16_t bytes_readed = 0;
  913. if(storage_file_open(file, SAVING_FILENAME, FSAM_READ, FSOM_OPEN_EXISTING)) {
  914. bytes_readed = storage_file_read(file, app, sizeof(AsteroidsApp));
  915. }
  916. storage_file_close(file);
  917. storage_file_free(file);
  918. furi_record_close(RECORD_STORAGE);
  919. return bytes_readed == sizeof(AsteroidsApp);
  920. }
  921. void save_game(AsteroidsApp* app) {
  922. Storage* storage = furi_record_open(RECORD_STORAGE);
  923. if(storage_common_stat(storage, SAVING_DIRECTORY, NULL) == FSE_NOT_EXIST) {
  924. if(!storage_simply_mkdir(storage, SAVING_DIRECTORY)) {
  925. return;
  926. }
  927. }
  928. File* file = storage_file_alloc(storage);
  929. if(storage_file_open(file, SAVING_FILENAME, FSAM_WRITE, FSOM_CREATE_ALWAYS)) {
  930. storage_file_write(file, app, sizeof(AsteroidsApp));
  931. }
  932. storage_file_close(file);
  933. storage_file_free(file);
  934. furi_record_close(RECORD_STORAGE);
  935. }
  936. /* Here all we do is putting the events into the queue that will be handled
  937. * in the while() loop of the app entry point function. */
  938. void input_callback(InputEvent* input_event, void* ctx) {
  939. AsteroidsApp* app = ctx;
  940. furi_message_queue_put(app->event_queue, input_event, FuriWaitForever);
  941. }
  942. /* Allocate the application state and initialize a number of stuff.
  943. * This is called in the entry point to create the application state. */
  944. AsteroidsApp* asteroids_app_alloc() {
  945. AsteroidsApp* app = malloc(sizeof(AsteroidsApp));
  946. load_game(app);
  947. app->gui = furi_record_open(RECORD_GUI);
  948. app->view_port = view_port_alloc();
  949. view_port_draw_callback_set(app->view_port, render_callback, app);
  950. view_port_input_callback_set(app->view_port, input_callback, app);
  951. gui_add_view_port(app->gui, app->view_port, GuiLayerFullscreen);
  952. app->event_queue = furi_message_queue_alloc(8, sizeof(InputEvent));
  953. app->running = 1; /* Turns 0 when back is pressed. */
  954. restart_game_after_gameover(app);
  955. memset(app->pressed, 0, sizeof(app->pressed));
  956. return app;
  957. }
  958. /* Free what the application allocated. It is not clear to me if the
  959. * Flipper OS, once the application exits, will be able to reclaim space
  960. * even if we forget to free something here. */
  961. void asteroids_app_free(AsteroidsApp* app) {
  962. furi_assert(app);
  963. // View related.
  964. view_port_enabled_set(app->view_port, false);
  965. gui_remove_view_port(app->gui, app->view_port);
  966. view_port_free(app->view_port);
  967. furi_record_close(RECORD_GUI);
  968. furi_message_queue_free(app->event_queue);
  969. app->gui = NULL;
  970. free(app);
  971. }
  972. /* Return the time in milliseconds the specified key is continuously
  973. * pressed. Or 0 if it is not pressed. */
  974. uint32_t key_pressed_time(AsteroidsApp* app, InputKey key) {
  975. return app->pressed[key] == 0 ? 0 : furi_get_tick() - app->pressed[key];
  976. }
  977. /* Handle keys interaction. */
  978. void asteroids_update_keypress_state(AsteroidsApp* app, InputEvent input) {
  979. // Allow Rapid fire
  980. if(input.key == InputKeyOk) {
  981. app->fire = true;
  982. }
  983. if(input.type == InputTypePress) {
  984. app->pressed[input.key] = furi_get_tick();
  985. } else if(input.type == InputTypeRelease) {
  986. app->pressed[input.key] = 0;
  987. }
  988. }
  989. int32_t asteroids_app_entry(void* p) {
  990. UNUSED(p);
  991. AsteroidsApp* app = asteroids_app_alloc();
  992. /* Create a timer. We do data analysis in the callback. */
  993. FuriTimer* timer = furi_timer_alloc(game_tick, FuriTimerTypePeriodic, app);
  994. furi_timer_start(timer, furi_kernel_get_tick_frequency() / 10);
  995. /* This is the main event loop: here we get the events that are pushed
  996. * in the queue by input_callback(), and process them one after the
  997. * other. */
  998. InputEvent input;
  999. while(app->running) {
  1000. FuriStatus qstat = furi_message_queue_get(app->event_queue, &input, 100);
  1001. if(qstat == FuriStatusOk) {
  1002. // if(DEBUG_MSG)
  1003. // FURI_LOG_E(TAG, "Main Loop - Input: type %d key %u", input.type, input.key);
  1004. /* Handle navigation here. Then handle view-specific inputs
  1005. * in the view specific handling function. */
  1006. if(input.type == InputTypeLong && input.key == InputKeyBack) {
  1007. // Save High Score even if player didn't finish game
  1008. if(app->is_new_highscore) save_game(app); // Save highscore but only on change
  1009. app->running = 0;
  1010. } else {
  1011. asteroids_update_keypress_state(app, input);
  1012. }
  1013. } else {
  1014. /* Useful to understand if the app is still alive when it
  1015. * does not respond because of bugs. */
  1016. if(DEBUG_MSG) {
  1017. static int c = 0;
  1018. c++;
  1019. if(!(c % 20)) FURI_LOG_E(TAG, "Loop timeout");
  1020. }
  1021. }
  1022. }
  1023. furi_timer_free(timer);
  1024. asteroids_app_free(app);
  1025. return 0;
  1026. }