app.c 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221
  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 5 /* Max bonus 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_powerUp_RemainingLife(Canvas* canvas, PowerUp* const p, int y_offset) {
  320. if(!p->isPowerUpActive) return;
  321. /*
  322. Here we generate a reverse progress bar. The bar is 24 pixels wide and 1 pixel tall.
  323. Calculate the percentage of hitpoints left: hitpoints / total hitpoints
  324. Multiply the percentage by the width of the bar (in pixels): percentage * bar width
  325. Subtract the result from the width of the bar to get the filled portion of the bar: bar width - (percentage * bar width)
  326. Round the result to the nearest integer to get the final result.
  327. 400 / 400 = 1.0
  328. 1.0 * 24 = 24
  329. 24 - 24 = 0
  330. Round(0) = 0
  331. */
  332. int progress_bar_width = SCREEN_XRES / 4;
  333. if(p->ttl > 0) {
  334. canvas_set_color(canvas, ColorBlack);
  335. int remaining = ceil(((float)p->ttl / (float)POWERUPSTTL) * (float)progress_bar_width);
  336. if(remaining > 0) {
  337. canvas_draw_line(
  338. canvas,
  339. (SCREEN_XRES / 2) - remaining, // x1
  340. 3 + y_offset, //y1
  341. (SCREEN_XRES / 2) + remaining, //x2
  342. 3 + y_offset); //
  343. }
  344. }
  345. }
  346. void draw_powerUps(Canvas* const canvas, PowerUp* const p) {
  347. /*
  348. * * * * * * * * * *
  349. * *
  350. * *
  351. * *
  352. * F *
  353. * *
  354. * *
  355. * *
  356. * *
  357. * * * * * * * * * *
  358. BOX_SIZE = 10
  359. Box_Width = BOX_SIZE
  360. BOX_HEIGHT = BOX_SIZE
  361. BOX_X_POS = x - BOX_WIDTH/2
  362. BOX_Y_POS = y - BOX_HEIGHT/2
  363. POS_F_X = WIDTH/2
  364. POS_F_Y = HEIGHT/2
  365. */
  366. //@todo render_callback
  367. // Just return if power up has already been picked up
  368. // FURI_LOG_I(TAG, "[draw_powerUps] Display TTL: %lu", p->display_ttl);
  369. if(p->display_ttl == 0) return;
  370. if(!should_draw_powerUp(p)) return;
  371. canvas_set_color(canvas, ColorXOR);
  372. // Display power up to be picked up
  373. switch(p->powerUpType) {
  374. case PowerUpTypeFirePower:
  375. canvas_draw_icon(canvas, p->x, p->y, &I_firepower_shifted_9x10);
  376. break;
  377. case PowerUpTypeShield:
  378. canvas_draw_icon(canvas, p->x, p->y, &I_shield_frame);
  379. break;
  380. case PowerUpTypeLife:
  381. // Draw a heart
  382. canvas_draw_icon(canvas, p->x, p->y, &I_heart_10x10);
  383. break;
  384. case PowerUpTypeNuke:
  385. // canvas_draw_disc(canvas, p->x, p->y, p->size);
  386. // canvas_draw_str(canvas, p->x, p->y, "N");
  387. canvas_draw_icon(canvas, p->x, p->y, &I_nuke_10x10);
  388. break;
  389. // case PowerUpTypeRadialFire:
  390. // // Draw box with letter R inside
  391. // canvas_draw_str(canvas, p->x, p->y, "R");
  392. // break;
  393. // case PowerUpTypeAssist:
  394. // // Draw box with letter A inside
  395. // canvas_draw_str(canvas, p->x, p->y, "A");
  396. // break;
  397. // case PowerUpTypeClone:
  398. // // Draw box with letter C inside
  399. // canvas_draw_str(canvas, p->x, p->y, "C");
  400. // break;
  401. default:
  402. //@todo Uknown Power Up Type Detected
  403. // Draw box with letter U inside
  404. canvas_draw_str(canvas, p->x, p->y, "?");
  405. FURI_LOG_E(TAG, "Unexpected Power Up Type Detected: %i", p->powerUpType);
  406. break;
  407. }
  408. }
  409. void draw_shield(Canvas* const canvas, AsteroidsApp* app) {
  410. if(isPowerUpActive(app, PowerUpTypeShield) == false) return;
  411. canvas_set_color(canvas, ColorXOR);
  412. // canvas_draw_disc(canvas, app->ship.x, app->ship.y, 4);
  413. canvas_draw_circle(canvas, app->ship.x, app->ship.y, 8);
  414. }
  415. /* Given the current position, update it according to the velocity and
  416. * wrap it back to the other side if the object went over the screen. */
  417. void update_pos_by_velocity(float* x, float* y, float vx, float vy) {
  418. /* Return back from one side to the other of the screen. */
  419. *x += vx;
  420. *y += vy;
  421. if(*x >= SCREEN_XRES)
  422. *x = 0;
  423. else if(*x < 0)
  424. *x = SCREEN_XRES - 1;
  425. if(*y >= SCREEN_YRES)
  426. *y = 0;
  427. else if(*y < 0)
  428. *y = SCREEN_YRES - 1;
  429. }
  430. /* Render the current game screen. */
  431. void render_callback(Canvas* const canvas, void* ctx) {
  432. AsteroidsApp* app = ctx;
  433. /* Clear screen. */
  434. canvas_set_color(canvas, ColorWhite);
  435. canvas_draw_box(canvas, 0, 0, SCREEN_XRES - 1, SCREEN_YRES - 1);
  436. /* Draw score. */
  437. canvas_set_color(canvas, ColorBlack);
  438. canvas_set_font(canvas, FontSecondary);
  439. char score[32];
  440. snprintf(score, sizeof(score), "%lu", app->score);
  441. canvas_draw_str(canvas, 0, 8, score);
  442. /* Draw left ships. */
  443. draw_left_lives(canvas, app);
  444. /* Draw ship, asteroids, bullets. */
  445. draw_poly(canvas, &ShipPoly, app->ship.x, app->ship.y, app->ship.rot);
  446. /* Draw shield if active. */
  447. draw_shield(canvas, app);
  448. if(key_pressed_time(app, InputKeyUp) > 0) {
  449. notification_message(furi_record_open(RECORD_NOTIFICATION), &sequence_thrusters);
  450. draw_poly(canvas, &ShipFirePoly, app->ship.x, app->ship.y, app->ship.rot);
  451. }
  452. for(int j = 0; j < app->bullets_num; j++) draw_bullet(canvas, &app->bullets[j]);
  453. for(int j = 0; j < app->asteroids_num; j++) draw_asteroid(canvas, &app->asteroids[j]);
  454. for(int j = 0; j < app->powerUps_num; j++) {
  455. draw_powerUps(canvas, &app->powerUps[j]);
  456. draw_powerUp_RemainingLife(canvas, &app->powerUps[j], j);
  457. }
  458. /* Game over text. */
  459. if(app->gameover) {
  460. canvas_set_color(canvas, ColorBlack);
  461. canvas_set_font(canvas, FontPrimary);
  462. // TODO: if new highscore, display blinking "New High Score"
  463. // Display High Score
  464. if(app->is_new_highscore) {
  465. canvas_draw_str(canvas, 22, 9, "New High Score!");
  466. } else {
  467. canvas_draw_str(canvas, 36, 9, "High Score");
  468. }
  469. // Convert highscore to string
  470. int length = snprintf(NULL, 0, "%lu", app->highscore);
  471. char* str_high_score = malloc(length + 1);
  472. snprintf(str_high_score, length + 1, "%lu", app->highscore);
  473. // Get length to center on screen
  474. int nDigits = 0;
  475. if(app->highscore > 0) {
  476. nDigits = floor(log10(app->highscore)) + 1;
  477. }
  478. // Draw highscore centered
  479. canvas_draw_str(canvas, (SCREEN_XRES / 2) - (nDigits * 2), 20, str_high_score);
  480. free(str_high_score);
  481. canvas_draw_str(canvas, 28, 35, "GAME OVER");
  482. canvas_set_font(canvas, FontSecondary);
  483. canvas_draw_str(canvas, 25, 50, "Press OK to restart");
  484. }
  485. }
  486. /* ============================ Game logic ================================== */
  487. float distance(float x1, float y1, float x2, float y2) {
  488. float dx = x1 - x2;
  489. float dy = y1 - y2;
  490. return sqrt(dx * dx + dy * dy);
  491. }
  492. /* Detect a collision between the object at x1,y1 of radius r1 and
  493. * the object at x2, y2 of radius r2. A factor < 1 will make the
  494. * function detect the collision even if the objects are yet not
  495. * relly touching, while a factor > 1 will make it detect the collision
  496. * only after they are a bit overlapping. It basically is used to
  497. * rescale the distance.
  498. *
  499. * Note that in this simplified 2D world, objects are all considered
  500. * spheres (this is why this function only takes the radius). This
  501. * is, after all, kinda accurate for asteroids, for bullets, and
  502. * even for the ship "core" itself. */
  503. bool objects_are_colliding(float x1, float y1, float r1, float x2, float y2, float r2, float factor) {
  504. /* The objects are colliding if the distance between object 1 and 2
  505. * is smaller than the sum of the two radiuses r1 and r2.
  506. * So it would be like: sqrt((x1-x2)^2+(y1-y2)^2) < r1+r2.
  507. * However we can avoid computing the sqrt (which is slow) by
  508. * squaring the second term and removing the square root, making
  509. * the comparison like this:
  510. *
  511. * (x1-x2)^2+(y1-y2)^2 < (r1+r2)^2. */
  512. float dx = (x1 - x2) * factor;
  513. float dy = (y1 - y2) * factor;
  514. float rsum = r1 + r2;
  515. return dx * dx + dy * dy < rsum * rsum;
  516. }
  517. //@todo ship_fire_bullet
  518. /* Create a new bullet headed in the same direction of the ship. */
  519. void ship_fire_bullet(AsteroidsApp* app) {
  520. // No power ups, only 5 bullets allowed
  521. if(isPowerUpActive(app, PowerUpTypeFirePower) == false && app->bullets_num >= 5) return;
  522. // Double the Fire Power
  523. if(isPowerUpActive(app, PowerUpTypeFirePower) && (app->bullets_num >= (MAXBUL))) return;
  524. notification_message(furi_record_open(RECORD_NOTIFICATION), &sequence_bullet_fired);
  525. Bullet* b = &app->bullets[app->bullets_num];
  526. b->x = app->ship.x;
  527. b->y = app->ship.y;
  528. b->vx = -sin(app->ship.rot);
  529. b->vy = cos(app->ship.rot);
  530. /* Ship should fire from its head, not in the middle. */
  531. b->x += b->vx * 5;
  532. b->y += b->vy * 5;
  533. /* Give the bullet some velocity (for now the vector is just
  534. * normalized to 1). */
  535. b->vx *= 3;
  536. b->vy *= 3;
  537. /* It's more realistic if we add the velocity vector of the
  538. * ship, too. Otherwise if the ship is going fast the bullets
  539. * will be slower, which is not how the world works. */
  540. b->vx += app->ship.vx;
  541. b->vy += app->ship.vy;
  542. b->ttl = TTLBUL; /* The bullet will disappear after N ticks. */
  543. app->bullets_num++;
  544. }
  545. /* Remove the specified bullet by id (index in the array). */
  546. void remove_bullet(AsteroidsApp* app, int bid) {
  547. /* Replace the top bullet with the empty space left
  548. * by the removal of this bullet. This way we always take the
  549. * array dense, which is an advantage when looping. */
  550. int n = --app->bullets_num;
  551. if(n && bid != n) app->bullets[bid] = app->bullets[n];
  552. }
  553. /* Create a new asteroid, away from the ship. Return the
  554. * pointer to the asteroid object, so that the caller can change
  555. * certain things of the asteroid if needed. */
  556. Asteroid* add_asteroid(AsteroidsApp* app) {
  557. if(app->asteroids_num == MAXAST) return NULL;
  558. float size = 4 + rand() % 15;
  559. float min_distance = 20;
  560. float x, y;
  561. do {
  562. x = rand() % SCREEN_XRES;
  563. y = rand() % SCREEN_YRES;
  564. } while(distance(app->ship.x, app->ship.y, x, y) < min_distance + size);
  565. Asteroid* a = &app->asteroids[app->asteroids_num++];
  566. a->x = x;
  567. a->y = y;
  568. a->vx = 2 * (-.5 + ((float)rand() / RAND_MAX));
  569. a->vy = 2 * (-.5 + ((float)rand() / RAND_MAX));
  570. a->size = size;
  571. a->rot = 0;
  572. a->rot_speed = ((float)rand() / RAND_MAX) / 10;
  573. if(app->ticks & 1) a->rot_speed = -(a->rot_speed);
  574. a->shape_seed = rand() & 255;
  575. return a;
  576. }
  577. /* Remove the specified asteroid by id (index in the array). */
  578. void remove_asteroid(AsteroidsApp* app, int id) {
  579. /* Replace the top asteroid with the empty space left
  580. * by the removal of this one. This way we always take the
  581. * array dense, which is an advantage when looping. */
  582. int n = --app->asteroids_num;
  583. if(n && id != n) app->asteroids[id] = app->asteroids[n];
  584. }
  585. /* Called when an asteroid was reached by a bullet. The asteroid
  586. * hit is the one with the specified 'id'. */
  587. void asteroid_was_hit(AsteroidsApp* app, int id) {
  588. float sizelimit = 6; // Smaller than that polverize in one shot.
  589. Asteroid* a = &app->asteroids[id];
  590. /* Asteroid is large enough to break into fragments. */
  591. float size = a->size;
  592. float x = a->x, y = a->y;
  593. remove_asteroid(app, id);
  594. if(size > sizelimit) {
  595. int max_fragments = size / sizelimit;
  596. int fragments = 2 + rand() % max_fragments;
  597. float newsize = size / fragments;
  598. if(newsize < 2) newsize = 2;
  599. for(int j = 0; j < fragments; j++) {
  600. a = add_asteroid(app);
  601. if(a == NULL) break; // Too many asteroids on screen.
  602. a->x = x + -(size / 2) + rand() % (int)newsize;
  603. a->y = y + -(size / 2) + rand() % (int)newsize;
  604. a->size = newsize;
  605. }
  606. } else {
  607. app->score++;
  608. if(app->score > app->highscore) {
  609. app->is_new_highscore = true;
  610. app->highscore = app->score; // Show on Game Over Screen and future main menu
  611. }
  612. }
  613. }
  614. bool isPowerUpCollidingWithEachOther(AsteroidsApp* app, float x, float y) {
  615. for(int i = 0; i < app->powerUps_num; i++) {
  616. PowerUp* p2 = &app->powerUps[i];
  617. if(distance(x, y, p2->x, p2->y) < p2->size) return true;
  618. }
  619. return false;
  620. }
  621. //@todo Add PowerUp
  622. PowerUp* add_powerUp(AsteroidsApp* app) {
  623. // FURI_LOG_I(TAG, "add_powerUp: %i", app->powerUps_num);
  624. if(app->powerUps_num == MAXPOWERUPS) return NULL;
  625. // Randomly select power up for display
  626. //@todo Random Power Up Select
  627. PowerUpType selected_powerUpType = rand() % Number_of_PowerUps;
  628. // PowerUpType selected_powerUpType = PowerUpTypeFirePower;
  629. // PowerUpType selected_powerUpType = PowerUpTypeLife;
  630. // PowerUpType selected_powerUpType = PowerUpTypeNuke;
  631. // PowerUpType selected_powerUpType = PowerUpTypeShield;
  632. // FURI_LOG_I(TAG, "[add_powerUp] Power Ups Active: %i", app->powerUps_num);
  633. // Don't add already existing power ups
  634. if(isPowerUpAlreadyExists(app, selected_powerUpType)) {
  635. FURI_LOG_D(TAG, "[add_powerUp] Power Up %i already active", selected_powerUpType);
  636. return NULL;
  637. }
  638. float size = 10;
  639. float min_distance = 20;
  640. float x, y;
  641. do {
  642. //size*2 to make sure power up is not spawned on the edge of the screen
  643. //It also keeps it away from the lives and score at the top of screen
  644. x = rand() % (SCREEN_XRES - (int)size);
  645. y = rand() % (SCREEN_YRES - (int)size);
  646. } while((distance(app->ship.x, app->ship.y, (float)x, (float)y) < min_distance + size) &&
  647. (!isPowerUpCollidingWithEachOther(app, x, y)));
  648. PowerUp* p = &app->powerUps[app->powerUps_num++];
  649. p->x = x;
  650. p->y = y;
  651. //@todo Disable Velocity
  652. p->vx = 0; //2 * (-.5 + ((float)rand() / RAND_MAX));
  653. p->vy = 0; //2 * (-.5 + ((float)rand() / RAND_MAX));
  654. p->display_ttl = 200;
  655. p->ttl = POWERUPSTTL;
  656. p->size = (int)size;
  657. // p->size = size;
  658. // p->rot = 0;
  659. // p->rot_speed = ((float)rand() / RAND_MAX) / 10;
  660. // if(app->ticks & 1) p->rot_speed = -(p->rot_speed);
  661. //@todo add powerup type, for now hardcoding to firepower
  662. p->powerUpType = selected_powerUpType;
  663. p->isPowerUpActive = false;
  664. return p;
  665. }
  666. //@todo remove_powerUp
  667. void remove_powerUp(AsteroidsApp* app, int id) {
  668. // Invalid ID, ignore
  669. if(id < 0) return;
  670. // TODO: Break this out into object types that set the game state
  671. if(app->powerUps[id].powerUpType == PowerUpTypeFirePower) {
  672. app->bullet_min_period = 200;
  673. }
  674. /* Replace the top powerUp with the empty space left
  675. * by the removal of this one. This way we always take the
  676. * array dense, which is an advantage when looping. */
  677. int n = --app->powerUps_num;
  678. if(n && id != n) app->powerUps[id] = app->powerUps[n];
  679. }
  680. void remove_all_astroids_and_bullets(AsteroidsApp* app) {
  681. app->score += app->asteroids_num;
  682. app->asteroids_num = 0;
  683. app->bullets_num = 0;
  684. }
  685. //@todo powerUp_was_hit
  686. void powerUp_was_hit(AsteroidsApp* app, int id) {
  687. PowerUp* p = &app->powerUps[id];
  688. if(p->display_ttl == 0) return; // Don't collect if already collected
  689. switch(p->powerUpType) {
  690. case PowerUpTypeLife:
  691. if(app->lives < MAXLIVES) app->lives++;
  692. remove_powerUp(app, id);
  693. break;
  694. case PowerUpTypeFirePower:
  695. p->ttl = POWERUPSTTL / 2;
  696. app->bullet_min_period = 100;
  697. break;
  698. case PowerUpTypeNuke:
  699. //TODO: Animate explosion
  700. notification_message(furi_record_open(RECORD_NOTIFICATION), &sequence_nuke);
  701. remove_all_astroids_and_bullets(app);
  702. break;
  703. default:
  704. break;
  705. }
  706. p->display_ttl = 0;
  707. p->isPowerUpActive = true;
  708. }
  709. bool isPowerUpActive(AsteroidsApp* const app, PowerUpType const powerUpType) {
  710. for(int i = 0; i < app->powerUps_num; i++) {
  711. // PowerUp* p = &app->powerUps[i];
  712. // if(p->powerUpType == powerUpType && p->ttl > 0 && p->display_ttl == 0) return true;
  713. if(app->powerUps[i].isPowerUpActive && app->powerUps[i].powerUpType == powerUpType) {
  714. return true;
  715. }
  716. }
  717. return false;
  718. }
  719. bool isPowerUpAlreadyExists(AsteroidsApp* const app, PowerUpType const powerUpType) {
  720. for(int i = 0; i < app->powerUps_num; i++) {
  721. if(app->powerUps[i].powerUpType == powerUpType) return true;
  722. }
  723. return false;
  724. }
  725. /* Set gameover state. When in game-over mode, the game displays a gameover
  726. * text with a background of many asteroids floating around. */
  727. void game_over(AsteroidsApp* app) {
  728. if(app->is_new_highscore) save_game(app); // Save highscore but only on change
  729. app->gameover = true;
  730. app->lives = GAME_START_LIVES; // Show 3 lives in game over screen to match new game start
  731. }
  732. /* Function called when a collision between the asteroid and the
  733. * ship is detected. */
  734. void ship_was_hit(AsteroidsApp* app) {
  735. app->ship_hit = SHIP_HIT_ANIMATION_LEN;
  736. if(app->lives) {
  737. app->lives--;
  738. } else {
  739. game_over(app);
  740. }
  741. }
  742. /* Restart game after the ship is hit. Will reset the ship position, bullets
  743. * and asteroids to restart the game. */
  744. void restart_game(AsteroidsApp* app) {
  745. app->ship.x = SCREEN_XRES / 2;
  746. app->ship.y = SCREEN_YRES / 2;
  747. app->ship.rot = PI; /* Start headed towards top. */
  748. app->ship.vx = 0;
  749. app->ship.vy = 0;
  750. app->bullets_num = 0;
  751. app->powerUps_num = 0;
  752. app->last_bullet_tick = 0;
  753. app->bullet_min_period = 200;
  754. app->asteroids_num = 0;
  755. app->ship_hit = 0;
  756. }
  757. /* Called after gameover to restart the game. This function
  758. * also calls restart_game(). */
  759. void restart_game_after_gameover(AsteroidsApp* app) {
  760. app->gameover = false;
  761. app->ticks = 0;
  762. app->score = 0;
  763. app->is_new_highscore = false;
  764. app->lives = GAME_START_LIVES - 1;
  765. restart_game(app);
  766. }
  767. /* Move bullets. */
  768. void update_bullets_position(AsteroidsApp* app) {
  769. for(int j = 0; j < app->bullets_num; j++) {
  770. update_pos_by_velocity(
  771. &app->bullets[j].x, &app->bullets[j].y, app->bullets[j].vx, app->bullets[j].vy);
  772. if(--app->bullets[j].ttl == 0) {
  773. remove_bullet(app, j);
  774. j--; /* Process this bullet index again: the removal will
  775. fill it with the top bullet to take the array dense. */
  776. }
  777. }
  778. }
  779. /* Move asteroids. */
  780. void update_asteroids_position(AsteroidsApp* app) {
  781. for(int j = 0; j < app->asteroids_num; j++) {
  782. update_pos_by_velocity(
  783. &app->asteroids[j].x, &app->asteroids[j].y, app->asteroids[j].vx, app->asteroids[j].vy);
  784. app->asteroids[j].rot += app->asteroids[j].rot_speed;
  785. if(app->asteroids[j].rot < 0)
  786. app->asteroids[j].rot = 2 * PI;
  787. else if(app->asteroids[j].rot > 2 * PI)
  788. app->asteroids[j].rot = 0;
  789. }
  790. }
  791. void update_powerUps_position(AsteroidsApp* app) {
  792. for(int j = 0; j < app->powerUps_num; j++) {
  793. // @todo update_powerUps_position
  794. if(app->powerUps[j].display_ttl > 0) {
  795. update_pos_by_velocity(
  796. &app->powerUps[j].x, &app->powerUps[j].y, app->powerUps[j].vx, app->powerUps[j].vy);
  797. }
  798. }
  799. }
  800. // @todo update_powerUp_status
  801. /* This updates the state of each power up collected and removes them if they have expired. */
  802. void update_powerUp_status(AsteroidsApp* app) {
  803. for(int j = app->powerUps_num; j >= 0; j--) {
  804. if(app->powerUps[j].ttl > 0 && app->powerUps[j].isPowerUpActive) {
  805. // Only decrement ttl if we actually picked up power up
  806. app->powerUps[j].ttl--;
  807. } else if(app->powerUps[j].display_ttl > 0) {
  808. app->powerUps[j].display_ttl--;
  809. } else {
  810. // we've reached the end of life of the power up
  811. // Time to remove it
  812. app->powerUps[j].isPowerUpActive = false;
  813. remove_powerUp(app, j);
  814. // j--; /* Process this power up index again: the removal will
  815. // fill it with the top power up to take the array dense. */
  816. }
  817. }
  818. }
  819. /* Collision detection and game state update based on collisions. */
  820. void detect_collisions(AsteroidsApp* app) {
  821. /* Detect collision between bullet and asteroid. */
  822. for(int j = 0; j < app->bullets_num; j++) {
  823. Bullet* b = &app->bullets[j];
  824. for(int i = 0; i < app->asteroids_num; i++) {
  825. Asteroid* a = &app->asteroids[i];
  826. if(objects_are_colliding(a->x, a->y, a->size, b->x, b->y, 1.5, 1)) {
  827. asteroid_was_hit(app, i);
  828. remove_bullet(app, j);
  829. /* The bullet no longer exist. Break the loop.
  830. * However we want to start processing from the
  831. * same bullet index, since now it is used by
  832. * another bullet (see remove_bullet()). */
  833. j--; /* Scan this j value again. */
  834. break;
  835. }
  836. }
  837. }
  838. /* Detect collision between ship and asteroid. */
  839. for(int j = 0; j < app->asteroids_num; j++) {
  840. Asteroid* a = &app->asteroids[j];
  841. if(objects_are_colliding(a->x, a->y, a->size, app->ship.x, app->ship.y, 4, 1)) {
  842. if(isPowerUpActive(app, PowerUpTypeShield)) {
  843. // Asteroid was hit with shield
  844. notification_message(
  845. furi_record_open(RECORD_NOTIFICATION), &sequence_bullet_fired);
  846. asteroid_was_hit(app, j);
  847. } else {
  848. // No sheild active, take damage
  849. ship_was_hit(app);
  850. }
  851. break;
  852. }
  853. }
  854. /* Detect collision between ship and powerUp. */
  855. for(int j = 0; j < app->powerUps_num; j++) {
  856. PowerUp* p = &app->powerUps[j];
  857. if(objects_are_colliding(p->x, p->y, p->size, app->ship.x, app->ship.y, 4, 1)) {
  858. powerUp_was_hit(app, j);
  859. break;
  860. }
  861. }
  862. }
  863. /* This is the main game execution function, called 10 times for
  864. * second (with the Flipper screen latency, an higher FPS does not
  865. * make sense). In this function we update the position of objects based
  866. * on velocity. Detect collisions. Update the score and so forth.
  867. *
  868. * Each time this function is called, app->tick is incremented. */
  869. void game_tick(void* ctx) {
  870. AsteroidsApp* app = ctx;
  871. /* There are two special screens:
  872. *
  873. * 1. Ship was hit, we frozen the game as long as ship_hit isn't zero
  874. * again, and show an animation of a rotating ship. */
  875. if(app->ship_hit) {
  876. notification_message(furi_record_open(RECORD_NOTIFICATION), &sequence_crash);
  877. app->ship.rot += 0.5;
  878. app->ship_hit--;
  879. view_port_update(app->view_port);
  880. if(app->ship_hit == 0) {
  881. restart_game(app);
  882. }
  883. return;
  884. } else if(app->gameover) {
  885. /* 2. Game over. We need to update only background asteroids. In this
  886. * state the game just displays a GAME OVER text with the floating
  887. * asteroids in backgroud. */
  888. if(key_pressed_time(app, InputKeyOk) > 100) {
  889. restart_game_after_gameover(app);
  890. }
  891. update_asteroids_position(app);
  892. view_port_update(app->view_port);
  893. return;
  894. }
  895. /* Handle keypresses. */
  896. if(app->pressed[InputKeyLeft]) app->ship.rot -= .35;
  897. if(app->pressed[InputKeyRight]) app->ship.rot += .35;
  898. if(app->pressed[InputKeyUp]) {
  899. app->ship.vx -= 0.5 * (float)sin(app->ship.rot);
  900. app->ship.vy += 0.5 * (float)cos(app->ship.rot);
  901. } else if(app->pressed[InputKeyDown]) {
  902. notification_message(furi_record_open(RECORD_NOTIFICATION), &sequence_brake);
  903. app->ship.vx *= 0.75;
  904. app->ship.vy *= 0.75;
  905. }
  906. /* Fire a bullet if needed. app->fire is set in
  907. * asteroids_update_keypress_state() since depends on exact
  908. * pressure timing. */
  909. if(app->fire) {
  910. uint32_t now = furi_get_tick();
  911. if(now - app->last_bullet_tick >= app->bullet_min_period) {
  912. ship_fire_bullet(app);
  913. app->last_bullet_tick = now;
  914. }
  915. app->fire = false;
  916. }
  917. // DEBUG: Show Power Up Status
  918. // for(int j = 0; j < app->powerUps_num; j++) {
  919. // PowerUp* p = &app->powerUps[j];
  920. // FURI_LOG_I(
  921. // TAG,
  922. // "Power Up Type: %d TTL: %lu Display_TTL: %lu PowerUpNum: %i",
  923. // p->powerUpType,
  924. // p->ttl,
  925. // p->display_ttl,
  926. // app->powerUps_num);
  927. // }
  928. /* Update positions and detect collisions. */
  929. update_pos_by_velocity(&app->ship.x, &app->ship.y, app->ship.vx, app->ship.vy);
  930. update_bullets_position(app);
  931. update_asteroids_position(app);
  932. update_powerUp_status(app); //@todo update_powerUp_status
  933. update_powerUps_position(app);
  934. detect_collisions(app);
  935. /* From time to time, create a new asteroid. The more asteroids
  936. * already on the screen, the smaller probability of creating
  937. * a new one. */
  938. if(app->asteroids_num == 0 || (random() % 5000) < (30 / (1 + app->asteroids_num))) {
  939. add_asteroid(app);
  940. }
  941. /* From time to time add a random power up */
  942. //@todo game tick
  943. if((app->powerUps_num == 0 || random() % 5000) < (30 / (1 + app->powerUps_num))) {
  944. add_powerUp(app);
  945. }
  946. app->ticks++;
  947. view_port_update(app->view_port);
  948. }
  949. /* ======================== Flipper specific code =========================== */
  950. bool load_game(AsteroidsApp* app) {
  951. Storage* storage = furi_record_open(RECORD_STORAGE);
  952. File* file = storage_file_alloc(storage);
  953. uint16_t bytes_readed = 0;
  954. if(storage_file_open(file, SAVING_FILENAME, FSAM_READ, FSOM_OPEN_EXISTING)) {
  955. bytes_readed = storage_file_read(file, app, sizeof(AsteroidsApp));
  956. }
  957. storage_file_close(file);
  958. storage_file_free(file);
  959. furi_record_close(RECORD_STORAGE);
  960. return bytes_readed == sizeof(AsteroidsApp);
  961. }
  962. void save_game(AsteroidsApp* app) {
  963. Storage* storage = furi_record_open(RECORD_STORAGE);
  964. if(storage_common_stat(storage, SAVING_DIRECTORY, NULL) == FSE_NOT_EXIST) {
  965. if(!storage_simply_mkdir(storage, SAVING_DIRECTORY)) {
  966. return;
  967. }
  968. }
  969. File* file = storage_file_alloc(storage);
  970. if(storage_file_open(file, SAVING_FILENAME, FSAM_WRITE, FSOM_CREATE_ALWAYS)) {
  971. storage_file_write(file, app, sizeof(AsteroidsApp));
  972. }
  973. storage_file_close(file);
  974. storage_file_free(file);
  975. furi_record_close(RECORD_STORAGE);
  976. }
  977. /* Here all we do is putting the events into the queue that will be handled
  978. * in the while() loop of the app entry point function. */
  979. void input_callback(InputEvent* input_event, void* ctx) {
  980. AsteroidsApp* app = ctx;
  981. furi_message_queue_put(app->event_queue, input_event, FuriWaitForever);
  982. }
  983. /* Allocate the application state and initialize a number of stuff.
  984. * This is called in the entry point to create the application state. */
  985. AsteroidsApp* asteroids_app_alloc() {
  986. AsteroidsApp* app = malloc(sizeof(AsteroidsApp));
  987. load_game(app);
  988. app->gui = furi_record_open(RECORD_GUI);
  989. app->view_port = view_port_alloc();
  990. view_port_draw_callback_set(app->view_port, render_callback, app);
  991. view_port_input_callback_set(app->view_port, input_callback, app);
  992. gui_add_view_port(app->gui, app->view_port, GuiLayerFullscreen);
  993. app->event_queue = furi_message_queue_alloc(8, sizeof(InputEvent));
  994. app->running = 1; /* Turns 0 when back is pressed. */
  995. restart_game_after_gameover(app);
  996. memset(app->pressed, 0, sizeof(app->pressed));
  997. return app;
  998. }
  999. /* Free what the application allocated. It is not clear to me if the
  1000. * Flipper OS, once the application exits, will be able to reclaim space
  1001. * even if we forget to free something here. */
  1002. void asteroids_app_free(AsteroidsApp* app) {
  1003. furi_assert(app);
  1004. // View related.
  1005. view_port_enabled_set(app->view_port, false);
  1006. gui_remove_view_port(app->gui, app->view_port);
  1007. view_port_free(app->view_port);
  1008. furi_record_close(RECORD_GUI);
  1009. furi_message_queue_free(app->event_queue);
  1010. app->gui = NULL;
  1011. free(app);
  1012. }
  1013. /* Return the time in milliseconds the specified key is continuously
  1014. * pressed. Or 0 if it is not pressed. */
  1015. uint32_t key_pressed_time(AsteroidsApp* app, InputKey key) {
  1016. return app->pressed[key] == 0 ? 0 : furi_get_tick() - app->pressed[key];
  1017. }
  1018. /* Handle keys interaction. */
  1019. void asteroids_update_keypress_state(AsteroidsApp* app, InputEvent input) {
  1020. // Allow Rapid fire
  1021. if(input.key == InputKeyOk) {
  1022. app->fire = true;
  1023. }
  1024. if(input.type == InputTypePress) {
  1025. app->pressed[input.key] = furi_get_tick();
  1026. } else if(input.type == InputTypeRelease) {
  1027. app->pressed[input.key] = 0;
  1028. }
  1029. }
  1030. int32_t asteroids_app_entry(void* p) {
  1031. UNUSED(p);
  1032. AsteroidsApp* app = asteroids_app_alloc();
  1033. /* Create a timer. We do data analysis in the callback. */
  1034. FuriTimer* timer = furi_timer_alloc(game_tick, FuriTimerTypePeriodic, app);
  1035. furi_timer_start(timer, furi_kernel_get_tick_frequency() / 10);
  1036. /* This is the main event loop: here we get the events that are pushed
  1037. * in the queue by input_callback(), and process them one after the
  1038. * other. */
  1039. InputEvent input;
  1040. while(app->running) {
  1041. FuriStatus qstat = furi_message_queue_get(app->event_queue, &input, 100);
  1042. if(qstat == FuriStatusOk) {
  1043. // if(DEBUG_MSG)
  1044. // FURI_LOG_E(TAG, "Main Loop - Input: type %d key %u", input.type, input.key);
  1045. /* Handle navigation here. Then handle view-specific inputs
  1046. * in the view specific handling function. */
  1047. if(input.type == InputTypeLong && input.key == InputKeyBack) {
  1048. // Save High Score even if player didn't finish game
  1049. if(app->is_new_highscore) save_game(app); // Save highscore but only on change
  1050. app->running = 0;
  1051. } else {
  1052. asteroids_update_keypress_state(app, input);
  1053. }
  1054. } else {
  1055. /* Useful to understand if the app is still alive when it
  1056. * does not respond because of bugs. */
  1057. if(DEBUG_MSG) {
  1058. static int c = 0;
  1059. c++;
  1060. if(!(c % 20)) FURI_LOG_E(TAG, "Loop timeout");
  1061. }
  1062. }
  1063. }
  1064. furi_timer_free(timer);
  1065. asteroids_app_free(app);
  1066. return 0;
  1067. }