app.c 41 KB

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