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