app.c 43 KB

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