app.c 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176
  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. j--; /* Process this power up index again: the removal will
  774. fill it with the top power up to take the array dense. */
  775. } else if(app->powerUps[j].display_ttl > 0) {
  776. app->powerUps[j].display_ttl--;
  777. }
  778. }
  779. }
  780. /* Collision detection and game state update based on collisions. */
  781. void detect_collisions(AsteroidsApp* app) {
  782. /* Detect collision between bullet and asteroid. */
  783. for(int j = 0; j < app->bullets_num; j++) {
  784. Bullet* b = &app->bullets[j];
  785. for(int i = 0; i < app->asteroids_num; i++) {
  786. Asteroid* a = &app->asteroids[i];
  787. if(objects_are_colliding(a->x, a->y, a->size, b->x, b->y, 1.5, 1)) {
  788. asteroid_was_hit(app, i);
  789. remove_bullet(app, j);
  790. /* The bullet no longer exist. Break the loop.
  791. * However we want to start processing from the
  792. * same bullet index, since now it is used by
  793. * another bullet (see remove_bullet()). */
  794. j--; /* Scan this j value again. */
  795. break;
  796. }
  797. }
  798. }
  799. /* Detect collision between ship and asteroid. */
  800. for(int j = 0; j < app->asteroids_num; j++) {
  801. Asteroid* a = &app->asteroids[j];
  802. if(objects_are_colliding(a->x, a->y, a->size, app->ship.x, app->ship.y, 4, 1)) {
  803. if(isPowerUpActive(app, PowerUpTypeShield)) {
  804. // Asteroid was hit with shield
  805. notification_message(
  806. furi_record_open(RECORD_NOTIFICATION), &sequence_bullet_fired);
  807. asteroid_was_hit(app, j);
  808. } else {
  809. // No sheild active, take damage
  810. ship_was_hit(app);
  811. }
  812. break;
  813. }
  814. }
  815. /* Detect collision between ship and powerUp. */
  816. for(int j = 0; j < app->powerUps_num; j++) {
  817. PowerUp* p = &app->powerUps[j];
  818. if(objects_are_colliding(p->x, p->y, p->size, app->ship.x, app->ship.y, 4, 1)) {
  819. powerUp_was_hit(app, j);
  820. break;
  821. }
  822. }
  823. }
  824. /* This is the main game execution function, called 10 times for
  825. * second (with the Flipper screen latency, an higher FPS does not
  826. * make sense). In this function we update the position of objects based
  827. * on velocity. Detect collisions. Update the score and so forth.
  828. *
  829. * Each time this function is called, app->tick is incremented. */
  830. void game_tick(void* ctx) {
  831. AsteroidsApp* app = ctx;
  832. /* There are two special screens:
  833. *
  834. * 1. Ship was hit, we frozen the game as long as ship_hit isn't zero
  835. * again, and show an animation of a rotating ship. */
  836. if(app->ship_hit) {
  837. notification_message(furi_record_open(RECORD_NOTIFICATION), &sequence_crash);
  838. app->ship.rot += 0.5;
  839. app->ship_hit--;
  840. view_port_update(app->view_port);
  841. if(app->ship_hit == 0) {
  842. restart_game(app);
  843. }
  844. return;
  845. } else if(app->gameover) {
  846. /* 2. Game over. We need to update only background asteroids. In this
  847. * state the game just displays a GAME OVER text with the floating
  848. * asteroids in backgroud. */
  849. if(key_pressed_time(app, InputKeyOk) > 100) {
  850. restart_game_after_gameover(app);
  851. }
  852. update_asteroids_position(app);
  853. view_port_update(app->view_port);
  854. return;
  855. }
  856. /* Handle keypresses. */
  857. if(app->pressed[InputKeyLeft]) app->ship.rot -= .35;
  858. if(app->pressed[InputKeyRight]) app->ship.rot += .35;
  859. if(app->pressed[InputKeyUp]) {
  860. app->ship.vx -= 0.5 * (float)sin(app->ship.rot);
  861. app->ship.vy += 0.5 * (float)cos(app->ship.rot);
  862. } else if(app->pressed[InputKeyDown]) {
  863. notification_message(furi_record_open(RECORD_NOTIFICATION), &sequence_brake);
  864. app->ship.vx *= 0.75;
  865. app->ship.vy *= 0.75;
  866. }
  867. /* Fire a bullet if needed. app->fire is set in
  868. * asteroids_update_keypress_state() since depends on exact
  869. * pressure timing. */
  870. if(app->fire) {
  871. uint32_t now = furi_get_tick();
  872. if(now - app->last_bullet_tick >= app->bullet_min_period) {
  873. ship_fire_bullet(app);
  874. app->last_bullet_tick = now;
  875. }
  876. app->fire = false;
  877. }
  878. // DEBUG: Show Power Up Status
  879. for(int j = 0; j < app->powerUps_num; j++) {
  880. PowerUp* p = &app->powerUps[j];
  881. FURI_LOG_I(
  882. TAG,
  883. "Power Up Type: %d TTL: %lu Display_TTL: %lu PowerUpNum: %i",
  884. p->powerUpType,
  885. p->ttl,
  886. p->display_ttl,
  887. app->powerUps_num);
  888. }
  889. /* Update positions and detect collisions. */
  890. update_pos_by_velocity(&app->ship.x, &app->ship.y, app->ship.vx, app->ship.vy);
  891. update_bullets_position(app);
  892. update_asteroids_position(app);
  893. update_powerUp_status(app); //@todo update_powerUp_status
  894. update_powerUps_position(app);
  895. detect_collisions(app);
  896. /* From time to time, create a new asteroid. The more asteroids
  897. * already on the screen, the smaller probability of creating
  898. * a new one. */
  899. if(app->asteroids_num == 0 || (random() % 5000) < (30 / (1 + app->asteroids_num))) {
  900. add_asteroid(app);
  901. }
  902. /* From time to time add a random power up */
  903. //@todo game tick
  904. if((app->powerUps_num == 0 || random() % 5000) < (30 / (1 + app->powerUps_num))) {
  905. add_powerUp(app);
  906. }
  907. app->ticks++;
  908. view_port_update(app->view_port);
  909. }
  910. /* ======================== Flipper specific code =========================== */
  911. bool load_game(AsteroidsApp* app) {
  912. Storage* storage = furi_record_open(RECORD_STORAGE);
  913. File* file = storage_file_alloc(storage);
  914. uint16_t bytes_readed = 0;
  915. if(storage_file_open(file, SAVING_FILENAME, FSAM_READ, FSOM_OPEN_EXISTING)) {
  916. bytes_readed = storage_file_read(file, app, sizeof(AsteroidsApp));
  917. }
  918. storage_file_close(file);
  919. storage_file_free(file);
  920. furi_record_close(RECORD_STORAGE);
  921. return bytes_readed == sizeof(AsteroidsApp);
  922. }
  923. void save_game(AsteroidsApp* app) {
  924. Storage* storage = furi_record_open(RECORD_STORAGE);
  925. if(storage_common_stat(storage, SAVING_DIRECTORY, NULL) == FSE_NOT_EXIST) {
  926. if(!storage_simply_mkdir(storage, SAVING_DIRECTORY)) {
  927. return;
  928. }
  929. }
  930. File* file = storage_file_alloc(storage);
  931. if(storage_file_open(file, SAVING_FILENAME, FSAM_WRITE, FSOM_CREATE_ALWAYS)) {
  932. storage_file_write(file, app, sizeof(AsteroidsApp));
  933. }
  934. storage_file_close(file);
  935. storage_file_free(file);
  936. furi_record_close(RECORD_STORAGE);
  937. }
  938. /* Here all we do is putting the events into the queue that will be handled
  939. * in the while() loop of the app entry point function. */
  940. void input_callback(InputEvent* input_event, void* ctx) {
  941. AsteroidsApp* app = ctx;
  942. furi_message_queue_put(app->event_queue, input_event, FuriWaitForever);
  943. }
  944. /* Allocate the application state and initialize a number of stuff.
  945. * This is called in the entry point to create the application state. */
  946. AsteroidsApp* asteroids_app_alloc() {
  947. AsteroidsApp* app = malloc(sizeof(AsteroidsApp));
  948. load_game(app);
  949. app->gui = furi_record_open(RECORD_GUI);
  950. app->view_port = view_port_alloc();
  951. view_port_draw_callback_set(app->view_port, render_callback, app);
  952. view_port_input_callback_set(app->view_port, input_callback, app);
  953. gui_add_view_port(app->gui, app->view_port, GuiLayerFullscreen);
  954. app->event_queue = furi_message_queue_alloc(8, sizeof(InputEvent));
  955. app->running = 1; /* Turns 0 when back is pressed. */
  956. restart_game_after_gameover(app);
  957. memset(app->pressed, 0, sizeof(app->pressed));
  958. return app;
  959. }
  960. /* Free what the application allocated. It is not clear to me if the
  961. * Flipper OS, once the application exits, will be able to reclaim space
  962. * even if we forget to free something here. */
  963. void asteroids_app_free(AsteroidsApp* app) {
  964. furi_assert(app);
  965. // View related.
  966. view_port_enabled_set(app->view_port, false);
  967. gui_remove_view_port(app->gui, app->view_port);
  968. view_port_free(app->view_port);
  969. furi_record_close(RECORD_GUI);
  970. furi_message_queue_free(app->event_queue);
  971. app->gui = NULL;
  972. free(app);
  973. }
  974. /* Return the time in milliseconds the specified key is continuously
  975. * pressed. Or 0 if it is not pressed. */
  976. uint32_t key_pressed_time(AsteroidsApp* app, InputKey key) {
  977. return app->pressed[key] == 0 ? 0 : furi_get_tick() - app->pressed[key];
  978. }
  979. /* Handle keys interaction. */
  980. void asteroids_update_keypress_state(AsteroidsApp* app, InputEvent input) {
  981. // Allow Rapid fire
  982. if(input.key == InputKeyOk) {
  983. app->fire = true;
  984. }
  985. if(input.type == InputTypePress) {
  986. app->pressed[input.key] = furi_get_tick();
  987. } else if(input.type == InputTypeRelease) {
  988. app->pressed[input.key] = 0;
  989. }
  990. }
  991. int32_t asteroids_app_entry(void* p) {
  992. UNUSED(p);
  993. AsteroidsApp* app = asteroids_app_alloc();
  994. /* Create a timer. We do data analysis in the callback. */
  995. FuriTimer* timer = furi_timer_alloc(game_tick, FuriTimerTypePeriodic, app);
  996. furi_timer_start(timer, furi_kernel_get_tick_frequency() / 10);
  997. /* This is the main event loop: here we get the events that are pushed
  998. * in the queue by input_callback(), and process them one after the
  999. * other. */
  1000. InputEvent input;
  1001. while(app->running) {
  1002. FuriStatus qstat = furi_message_queue_get(app->event_queue, &input, 100);
  1003. if(qstat == FuriStatusOk) {
  1004. // if(DEBUG_MSG)
  1005. // FURI_LOG_E(TAG, "Main Loop - Input: type %d key %u", input.type, input.key);
  1006. /* Handle navigation here. Then handle view-specific inputs
  1007. * in the view specific handling function. */
  1008. if(input.type == InputTypeLong && input.key == InputKeyBack) {
  1009. // Save High Score even if player didn't finish game
  1010. if(app->is_new_highscore) save_game(app); // Save highscore but only on change
  1011. app->running = 0;
  1012. } else {
  1013. asteroids_update_keypress_state(app, input);
  1014. }
  1015. } else {
  1016. /* Useful to understand if the app is still alive when it
  1017. * does not respond because of bugs. */
  1018. if(DEBUG_MSG) {
  1019. static int c = 0;
  1020. c++;
  1021. if(!(c % 20)) FURI_LOG_E(TAG, "Loop timeout");
  1022. }
  1023. }
  1024. }
  1025. furi_timer_free(timer);
  1026. asteroids_app_free(app);
  1027. return 0;
  1028. }