app.c 41 KB

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