app.c 42 KB

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