app.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787
  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. #define TAG "Asteroids" // Used for logging
  16. #define DEBUG_MSG 1
  17. #define SCREEN_XRES 128
  18. #define SCREEN_YRES 64
  19. #define GAME_START_LIVES 3
  20. #define TTLBUL 30 /* Bullet time to live, in ticks. */
  21. #define MAXBUL 5 /* Max bullets on the screen. */
  22. #define MAXAST 32 /* Max asteroids on the screen. */
  23. #define SHIP_HIT_ANIMATION_LEN 15
  24. #define SAVING_DIRECTORY "/ext/apps/Games"
  25. #define SAVING_FILENAME SAVING_DIRECTORY "/game_asteroids.save"
  26. #ifndef PI
  27. #define PI 3.14159265358979f
  28. #endif
  29. /* ============================ Data structures ============================= */
  30. typedef struct Ship {
  31. float x, /* Ship x position. */
  32. y, /* Ship y position. */
  33. vx, /* x velocity. */
  34. vy, /* y velocity. */
  35. rot; /* Current rotation. 2*PI full ortation. */
  36. } Ship;
  37. typedef struct Bullet {
  38. float x, y, vx, vy; /* Fields like in ship. */
  39. uint32_t ttl; /* Time to live, in ticks. */
  40. } Bullet;
  41. typedef struct Asteroid {
  42. float x, y, vx, vy, rot, /* Fields like ship. */
  43. rot_speed, /* Angular velocity (rot speed and sense). */
  44. size; /* Asteroid size. */
  45. uint8_t shape_seed; /* Seed to give random shape. */
  46. } Asteroid;
  47. typedef struct AsteroidsApp {
  48. /* GUI */
  49. Gui* gui;
  50. ViewPort* view_port; /* We just use a raw viewport and we render
  51. everything into the low level canvas. */
  52. FuriMessageQueue* event_queue; /* Keypress events go here. */
  53. /* Game state. */
  54. int running; /* Once false exists the app. */
  55. bool gameover; /* Gameover status. */
  56. uint32_t ticks; /* Game ticks. Increments at each refresh. */
  57. uint32_t score; /* Game score. */
  58. uint32_t highscore; /* Highscore. Shown on Game Over Screen */
  59. bool is_new_highscore; /* Is the last score a new highscore? */
  60. uint32_t lives; /* Number of lives in the current game. */
  61. uint32_t ship_hit; /* When non zero, the ship was hit by an asteroid
  62. and we need to show an animation as long as
  63. its value is non-zero (and decrease it's value
  64. at each tick of animation). */
  65. /* Ship state. */
  66. struct Ship ship;
  67. /* Bullets state. */
  68. struct Bullet bullets[MAXBUL]; /* Each bullet state. */
  69. int bullets_num; /* Active bullets. */
  70. uint32_t last_bullet_tick; /* Tick the last bullet was fired. */
  71. /* Asteroids state. */
  72. Asteroid asteroids[MAXAST]; /* Each asteroid state. */
  73. int asteroids_num; /* Active asteroids. */
  74. uint32_t pressed[InputKeyMAX]; /* pressed[id] is true if pressed.
  75. Each array item contains the time
  76. in milliseconds the key was pressed. */
  77. bool fire; /* Short press detected: fire a bullet. */
  78. } AsteroidsApp;
  79. const NotificationSequence sequence_thrusters = {
  80. &message_vibro_on,
  81. &message_delay_10,
  82. &message_vibro_off,
  83. NULL,
  84. };
  85. const NotificationSequence sequence_brake = {
  86. &message_vibro_on,
  87. &message_delay_10,
  88. &message_delay_1,
  89. &message_delay_1,
  90. &message_vibro_off,
  91. NULL,
  92. };
  93. const NotificationSequence sequence_crash = {
  94. &message_red_255,
  95. &message_vibro_on,
  96. // &message_note_g5, // Play sound but currently disabled
  97. &message_delay_25,
  98. // &message_note_e5,
  99. &message_vibro_off,
  100. &message_sound_off,
  101. NULL,
  102. };
  103. const NotificationSequence sequence_bullet_fired = {
  104. &message_vibro_on,
  105. // &message_note_g5, // Play sound but currently disabled. Need On/Off menu setting
  106. &message_delay_10,
  107. &message_delay_1,
  108. &message_delay_1,
  109. &message_delay_1,
  110. &message_delay_1,
  111. &message_delay_1,
  112. // &message_note_e5,
  113. &message_vibro_off,
  114. &message_sound_off,
  115. NULL,
  116. };
  117. /* ============================== Prototyeps ================================ */
  118. // Only functions called before their definition are here.
  119. bool load_game(AsteroidsApp* app);
  120. void save_game(AsteroidsApp* app);
  121. void restart_game_after_gameover(AsteroidsApp* app);
  122. uint32_t key_pressed_time(AsteroidsApp* app, InputKey key);
  123. /* ============================ 2D drawing ================================== */
  124. /* This structure represents a polygon of at most POLY_MAX points.
  125. * The function draw_poly() is able to render it on the screen, rotated
  126. * by the amount specified. */
  127. #define POLY_MAX 8
  128. typedef struct Poly {
  129. float x[POLY_MAX];
  130. float y[POLY_MAX];
  131. uint32_t points; /* Number of points actually populated. */
  132. } Poly;
  133. /* Define the polygons we use. */
  134. Poly ShipPoly = {{-3, 0, 3}, {-3, 6, -3}, 3};
  135. Poly ShipFirePoly = {{-1.5, 0, 1.5}, {-3, -6, -3}, 3};
  136. /* Rotate the point of the poligon 'poly' and store the new rotated
  137. * polygon in 'rot'. The polygon is rotated by an angle 'a', with
  138. * center at 0,0. */
  139. void rotate_poly(Poly* rot, Poly* poly, float a) {
  140. /* We want to compute sin(a) and cos(a) only one time
  141. * for every point to rotate. It's a slow operation. */
  142. float sin_a = (float)sin(a);
  143. float cos_a = (float)cos(a);
  144. for(uint32_t j = 0; j < poly->points; j++) {
  145. rot->x[j] = poly->x[j] * cos_a - poly->y[j] * sin_a;
  146. rot->y[j] = poly->y[j] * cos_a + poly->x[j] * sin_a;
  147. }
  148. rot->points = poly->points;
  149. }
  150. /* This is an 8 bit LFSR we use to generate a predictable and fast
  151. * pseudorandom sequence of numbers, to give a different shape to
  152. * each asteroid. */
  153. void lfsr_next(unsigned char* prev) {
  154. unsigned char lsb = *prev & 1;
  155. *prev = *prev >> 1;
  156. if(lsb == 1) *prev ^= 0b11000111;
  157. *prev ^= *prev << 7; /* Mix things a bit more. */
  158. }
  159. /* Render the polygon 'poly' at x,y, rotated by the specified angle. */
  160. void draw_poly(Canvas* const canvas, Poly* poly, uint8_t x, uint8_t y, float a) {
  161. Poly rot;
  162. rotate_poly(&rot, poly, a);
  163. canvas_set_color(canvas, ColorBlack);
  164. for(uint32_t j = 0; j < rot.points; j++) {
  165. uint32_t a = j;
  166. uint32_t b = j + 1;
  167. if(b == rot.points) b = 0;
  168. canvas_draw_line(canvas, x + rot.x[a], y + rot.y[a], x + rot.x[b], y + rot.y[b]);
  169. }
  170. }
  171. /* A bullet is just a + pixels pattern. A single pixel is not
  172. * visible enough. */
  173. void draw_bullet(Canvas* const canvas, Bullet* b) {
  174. canvas_draw_dot(canvas, b->x - 1, b->y);
  175. canvas_draw_dot(canvas, b->x + 1, b->y);
  176. canvas_draw_dot(canvas, b->x, b->y);
  177. canvas_draw_dot(canvas, b->x, b->y - 1);
  178. canvas_draw_dot(canvas, b->x, b->y + 1);
  179. }
  180. /* Draw an asteroid. The asteroid shapes is computed on the fly and
  181. * is not stored in a permanent shape structure. In order to generate
  182. * the shape, we use an initial fixed shape that we resize according
  183. * to the asteroid size, perturbate according to the asteroid shape
  184. * seed, and finally draw it rotated of the right amount. */
  185. void draw_asteroid(Canvas* const canvas, Asteroid* ast) {
  186. Poly ap;
  187. /* Start with what is kinda of a circle. Note that this could be
  188. * stored into a template and copied here, to avoid computing
  189. * sin() / cos(). But the Flipper can handle it without problems. */
  190. uint8_t r = ast->shape_seed;
  191. for(int j = 0; j < 8; j++) {
  192. float a = (PI * 2) / 8 * j;
  193. /* Before generating the point, to make the shape unique generate
  194. * a random factor between .7 and 1.3 to scale the distance from
  195. * the center. However this asteroid should have its unique shape
  196. * that remains always the same, so we use a predictable PRNG
  197. * implemented by an 8 bit shift register. */
  198. lfsr_next(&r);
  199. float scaling = .7 + ((float)r / 255 * .6);
  200. ap.x[j] = (float)sin(a) * ast->size * scaling;
  201. ap.y[j] = (float)cos(a) * ast->size * scaling;
  202. }
  203. ap.points = 8;
  204. draw_poly(canvas, &ap, ast->x, ast->y, ast->rot);
  205. }
  206. /* Draw small ships in the top-right part of the screen, one for
  207. * each left live. */
  208. void draw_left_lives(Canvas* const canvas, AsteroidsApp* app) {
  209. int lives = app->lives;
  210. int x = SCREEN_XRES - 5;
  211. Poly mini_ship = {{-2, 0, 2}, {-2, 4, -2}, 3};
  212. while(lives--) {
  213. draw_poly(canvas, &mini_ship, x, 6, PI);
  214. x -= 6;
  215. }
  216. }
  217. /* Given the current position, update it according to the velocity and
  218. * wrap it back to the other side if the object went over the screen. */
  219. void update_pos_by_velocity(float* x, float* y, float vx, float vy) {
  220. /* Return back from one side to the other of the screen. */
  221. *x += vx;
  222. *y += vy;
  223. if(*x >= SCREEN_XRES)
  224. *x = 0;
  225. else if(*x < 0)
  226. *x = SCREEN_XRES - 1;
  227. if(*y >= SCREEN_YRES)
  228. *y = 0;
  229. else if(*y < 0)
  230. *y = SCREEN_YRES - 1;
  231. }
  232. /* Render the current game screen. */
  233. void render_callback(Canvas* const canvas, void* ctx) {
  234. AsteroidsApp* app = ctx;
  235. /* Clear screen. */
  236. canvas_set_color(canvas, ColorWhite);
  237. canvas_draw_box(canvas, 0, 0, SCREEN_XRES - 1, SCREEN_YRES - 1);
  238. /* Draw score. */
  239. canvas_set_color(canvas, ColorBlack);
  240. canvas_set_font(canvas, FontSecondary);
  241. char score[32];
  242. snprintf(score, sizeof(score), "%lu", app->score);
  243. canvas_draw_str(canvas, 0, 8, score);
  244. /* Draw left ships. */
  245. draw_left_lives(canvas, app);
  246. /* Draw ship, asteroids, bullets. */
  247. draw_poly(canvas, &ShipPoly, app->ship.x, app->ship.y, app->ship.rot);
  248. if(key_pressed_time(app, InputKeyUp) > 0) {
  249. notification_message(furi_record_open(RECORD_NOTIFICATION), &sequence_thrusters);
  250. draw_poly(canvas, &ShipFirePoly, app->ship.x, app->ship.y, app->ship.rot);
  251. }
  252. for(int j = 0; j < app->bullets_num; j++) draw_bullet(canvas, &app->bullets[j]);
  253. for(int j = 0; j < app->asteroids_num; j++) draw_asteroid(canvas, &app->asteroids[j]);
  254. /* Game over text. */
  255. if(app->gameover) {
  256. canvas_set_color(canvas, ColorBlack);
  257. canvas_set_font(canvas, FontPrimary);
  258. // TODO: if new highscore, display blinking "New High Score"
  259. // Display High Score
  260. if(app->is_new_highscore) {
  261. canvas_draw_str(canvas, 22, 9, "New High Score!");
  262. } else {
  263. canvas_draw_str(canvas, 36, 9, "High Score");
  264. }
  265. // Convert highscore to string
  266. int length = snprintf(NULL, 0, "%lu", app->highscore);
  267. char* str_high_score = malloc(length + 1);
  268. snprintf(str_high_score, length + 1, "%lu", app->highscore);
  269. // Get length to center on screen
  270. int nDigits = 0;
  271. if(app->highscore > 0) {
  272. nDigits = floor(log10(app->highscore)) + 1;
  273. }
  274. // Draw highscore centered
  275. canvas_draw_str(canvas, (SCREEN_XRES / 2) - (nDigits * 2), 20, str_high_score);
  276. free(str_high_score);
  277. canvas_draw_str(canvas, 28, 35, "GAME OVER");
  278. canvas_set_font(canvas, FontSecondary);
  279. canvas_draw_str(canvas, 25, 50, "Press OK to restart");
  280. }
  281. }
  282. /* ============================ Game logic ================================== */
  283. float distance(float x1, float y1, float x2, float y2) {
  284. float dx = x1 - x2;
  285. float dy = y1 - y2;
  286. return sqrt(dx * dx + dy * dy);
  287. }
  288. /* Detect a collision between the object at x1,y1 of radius r1 and
  289. * the object at x2, y2 of radius r2. A factor < 1 will make the
  290. * function detect the collision even if the objects are yet not
  291. * relly touching, while a factor > 1 will make it detect the collision
  292. * only after they are a bit overlapping. It basically is used to
  293. * rescale the distance.
  294. *
  295. * Note that in this simplified 2D world, objects are all considered
  296. * spheres (this is why this function only takes the radius). This
  297. * is, after all, kinda accurate for asteroids, for bullets, and
  298. * even for the ship "core" itself. */
  299. bool objects_are_colliding(float x1, float y1, float r1, float x2, float y2, float r2, float factor) {
  300. /* The objects are colliding if the distance between object 1 and 2
  301. * is smaller than the sum of the two radiuses r1 and r2.
  302. * So it would be like: sqrt((x1-x2)^2+(y1-y2)^2) < r1+r2.
  303. * However we can avoid computing the sqrt (which is slow) by
  304. * squaring the second term and removing the square root, making
  305. * the comparison like this:
  306. *
  307. * (x1-x2)^2+(y1-y2)^2 < (r1+r2)^2. */
  308. float dx = (x1 - x2) * factor;
  309. float dy = (y1 - y2) * factor;
  310. float rsum = r1 + r2;
  311. return dx * dx + dy * dy < rsum * rsum;
  312. }
  313. /* Create a new bullet headed in the same direction of the ship. */
  314. void ship_fire_bullet(AsteroidsApp* app) {
  315. if(app->bullets_num == MAXBUL) return;
  316. notification_message(furi_record_open(RECORD_NOTIFICATION), &sequence_bullet_fired);
  317. Bullet* b = &app->bullets[app->bullets_num];
  318. b->x = app->ship.x;
  319. b->y = app->ship.y;
  320. b->vx = -sin(app->ship.rot);
  321. b->vy = cos(app->ship.rot);
  322. /* Ship should fire from its head, not in the middle. */
  323. b->x += b->vx * 5;
  324. b->y += b->vy * 5;
  325. /* Give the bullet some velocity (for now the vector is just
  326. * normalized to 1). */
  327. b->vx *= 3;
  328. b->vy *= 3;
  329. /* It's more realistic if we add the velocity vector of the
  330. * ship, too. Otherwise if the ship is going fast the bullets
  331. * will be slower, which is not how the world works. */
  332. b->vx += app->ship.vx;
  333. b->vy += app->ship.vy;
  334. b->ttl = TTLBUL; /* The bullet will disappear after N ticks. */
  335. app->bullets_num++;
  336. }
  337. /* Remove the specified bullet by id (index in the array). */
  338. void remove_bullet(AsteroidsApp* app, int bid) {
  339. /* Replace the top bullet with the empty space left
  340. * by the removal of this bullet. This way we always take the
  341. * array dense, which is an advantage when looping. */
  342. int n = --app->bullets_num;
  343. if(n && bid != n) app->bullets[bid] = app->bullets[n];
  344. }
  345. /* Create a new asteroid, away from the ship. Return the
  346. * pointer to the asteroid object, so that the caller can change
  347. * certain things of the asteroid if needed. */
  348. Asteroid* add_asteroid(AsteroidsApp* app) {
  349. if(app->asteroids_num == MAXAST) return NULL;
  350. float size = 4 + rand() % 15;
  351. float min_distance = 20;
  352. float x, y;
  353. do {
  354. x = rand() % SCREEN_XRES;
  355. y = rand() % SCREEN_YRES;
  356. } while(distance(app->ship.x, app->ship.y, x, y) < min_distance + size);
  357. Asteroid* a = &app->asteroids[app->asteroids_num++];
  358. a->x = x;
  359. a->y = y;
  360. a->vx = 2 * (-.5 + ((float)rand() / RAND_MAX));
  361. a->vy = 2 * (-.5 + ((float)rand() / RAND_MAX));
  362. a->size = size;
  363. a->rot = 0;
  364. a->rot_speed = ((float)rand() / RAND_MAX) / 10;
  365. if(app->ticks & 1) a->rot_speed = -(a->rot_speed);
  366. a->shape_seed = rand() & 255;
  367. return a;
  368. }
  369. /* Remove the specified asteroid by id (index in the array). */
  370. void remove_asteroid(AsteroidsApp* app, int id) {
  371. /* Replace the top asteroid with the empty space left
  372. * by the removal of this one. This way we always take the
  373. * array dense, which is an advantage when looping. */
  374. int n = --app->asteroids_num;
  375. if(n && id != n) app->asteroids[id] = app->asteroids[n];
  376. }
  377. /* Called when an asteroid was reached by a bullet. The asteroid
  378. * hit is the one with the specified 'id'. */
  379. void asteroid_was_hit(AsteroidsApp* app, int id) {
  380. float sizelimit = 6; // Smaller than that polverize in one shot.
  381. Asteroid* a = &app->asteroids[id];
  382. /* Asteroid is large enough to break into fragments. */
  383. float size = a->size;
  384. float x = a->x, y = a->y;
  385. remove_asteroid(app, id);
  386. if(size > sizelimit) {
  387. int max_fragments = size / sizelimit;
  388. int fragments = 2 + rand() % max_fragments;
  389. float newsize = size / fragments;
  390. if(newsize < 2) newsize = 2;
  391. for(int j = 0; j < fragments; j++) {
  392. a = add_asteroid(app);
  393. if(a == NULL) break; // Too many asteroids on screen.
  394. a->x = x + -(size / 2) + rand() % (int)newsize;
  395. a->y = y + -(size / 2) + rand() % (int)newsize;
  396. a->size = newsize;
  397. }
  398. } else {
  399. app->score++;
  400. if(app->score > app->highscore) {
  401. app->is_new_highscore = true;
  402. app->highscore = app->score; // Show on Game Over Screen and future main menu
  403. }
  404. }
  405. }
  406. /* Set gameover state. When in game-over mode, the game displays a gameover
  407. * text with a background of many asteroids floating around. */
  408. void game_over(AsteroidsApp* app) {
  409. save_game(app); // Save highscore
  410. app->gameover = true;
  411. app->lives = GAME_START_LIVES; // Show 3 lives in game over screen to match new game start
  412. }
  413. /* Function called when a collision between the asteroid and the
  414. * ship is detected. */
  415. void ship_was_hit(AsteroidsApp* app) {
  416. app->ship_hit = SHIP_HIT_ANIMATION_LEN;
  417. if(app->lives) {
  418. app->lives--;
  419. } else {
  420. game_over(app);
  421. }
  422. }
  423. /* Restart game after the ship is hit. Will reset the ship position, bullets
  424. * and asteroids to restart the game. */
  425. void restart_game(AsteroidsApp* app) {
  426. app->ship.x = SCREEN_XRES / 2;
  427. app->ship.y = SCREEN_YRES / 2;
  428. app->ship.rot = PI; /* Start headed towards top. */
  429. app->ship.vx = 0;
  430. app->ship.vy = 0;
  431. app->bullets_num = 0;
  432. app->last_bullet_tick = 0;
  433. app->asteroids_num = 0;
  434. app->ship_hit = 0;
  435. }
  436. /* Called after gameover to restart the game. This function
  437. * also calls restart_game(). */
  438. void restart_game_after_gameover(AsteroidsApp* app) {
  439. app->gameover = false;
  440. app->ticks = 0;
  441. app->score = 0;
  442. app->is_new_highscore = false;
  443. app->lives = GAME_START_LIVES - 1;
  444. restart_game(app);
  445. }
  446. /* Move bullets. */
  447. void update_bullets_position(AsteroidsApp* app) {
  448. for(int j = 0; j < app->bullets_num; j++) {
  449. update_pos_by_velocity(
  450. &app->bullets[j].x, &app->bullets[j].y, app->bullets[j].vx, app->bullets[j].vy);
  451. if(--app->bullets[j].ttl == 0) {
  452. remove_bullet(app, j);
  453. j--; /* Process this bullet index again: the removal will
  454. fill it with the top bullet to take the array dense. */
  455. }
  456. }
  457. }
  458. /* Move asteroids. */
  459. void update_asteroids_position(AsteroidsApp* app) {
  460. for(int j = 0; j < app->asteroids_num; j++) {
  461. update_pos_by_velocity(
  462. &app->asteroids[j].x, &app->asteroids[j].y, app->asteroids[j].vx, app->asteroids[j].vy);
  463. app->asteroids[j].rot += app->asteroids[j].rot_speed;
  464. if(app->asteroids[j].rot < 0)
  465. app->asteroids[j].rot = 2 * PI;
  466. else if(app->asteroids[j].rot > 2 * PI)
  467. app->asteroids[j].rot = 0;
  468. }
  469. }
  470. /* Collision detection and game state update based on collisions. */
  471. void detect_collisions(AsteroidsApp* app) {
  472. /* Detect collision between bullet and asteroid. */
  473. for(int j = 0; j < app->bullets_num; j++) {
  474. Bullet* b = &app->bullets[j];
  475. for(int i = 0; i < app->asteroids_num; i++) {
  476. Asteroid* a = &app->asteroids[i];
  477. if(objects_are_colliding(a->x, a->y, a->size, b->x, b->y, 1.5, 1)) {
  478. asteroid_was_hit(app, i);
  479. remove_bullet(app, j);
  480. /* The bullet no longer exist. Break the loop.
  481. * However we want to start processing from the
  482. * same bullet index, since now it is used by
  483. * another bullet (see remove_bullet()). */
  484. j--; /* Scan this j value again. */
  485. break;
  486. }
  487. }
  488. }
  489. /* Detect collision between ship and asteroid. */
  490. for(int j = 0; j < app->asteroids_num; j++) {
  491. Asteroid* a = &app->asteroids[j];
  492. if(objects_are_colliding(a->x, a->y, a->size, app->ship.x, app->ship.y, 4, 1)) {
  493. ship_was_hit(app);
  494. break;
  495. }
  496. }
  497. }
  498. /* This is the main game execution function, called 10 times for
  499. * second (with the Flipper screen latency, an higher FPS does not
  500. * make sense). In this function we update the position of objects based
  501. * on velocity. Detect collisions. Update the score and so forth.
  502. *
  503. * Each time this function is called, app->tick is incremented. */
  504. void game_tick(void* ctx) {
  505. AsteroidsApp* app = ctx;
  506. /* There are two special screens:
  507. *
  508. * 1. Ship was hit, we frozen the game as long as ship_hit isn't zero
  509. * again, and show an animation of a rotating ship. */
  510. if(app->ship_hit) {
  511. notification_message(furi_record_open(RECORD_NOTIFICATION), &sequence_crash);
  512. app->ship.rot += 0.5;
  513. app->ship_hit--;
  514. view_port_update(app->view_port);
  515. if(app->ship_hit == 0) {
  516. restart_game(app);
  517. }
  518. return;
  519. } else if(app->gameover) {
  520. /* 2. Game over. We need to update only background asteroids. In this
  521. * state the game just displays a GAME OVER text with the floating
  522. * asteroids in backgroud. */
  523. if(key_pressed_time(app, InputKeyOk) > 100) {
  524. restart_game_after_gameover(app);
  525. }
  526. update_asteroids_position(app);
  527. view_port_update(app->view_port);
  528. return;
  529. }
  530. /* Handle keypresses. */
  531. if(app->pressed[InputKeyLeft]) app->ship.rot -= .35;
  532. if(app->pressed[InputKeyRight]) app->ship.rot += .35;
  533. if(app->pressed[InputKeyUp]) {
  534. app->ship.vx -= 0.5 * (float)sin(app->ship.rot);
  535. app->ship.vy += 0.5 * (float)cos(app->ship.rot);
  536. } else if(app->pressed[InputKeyDown]) {
  537. notification_message(furi_record_open(RECORD_NOTIFICATION), &sequence_brake);
  538. app->ship.vx *= 0.75;
  539. app->ship.vy *= 0.75;
  540. }
  541. /* Fire a bullet if needed. app->fire is set in
  542. * asteroids_update_keypress_state() since depends on exact
  543. * pressure timing. */
  544. if(app->fire) {
  545. uint32_t bullet_min_period = 200; // In milliseconds
  546. uint32_t now = furi_get_tick();
  547. if(now - app->last_bullet_tick >= bullet_min_period) {
  548. ship_fire_bullet(app);
  549. app->last_bullet_tick = now;
  550. }
  551. app->fire = false;
  552. }
  553. /* Update positions and detect collisions. */
  554. update_pos_by_velocity(&app->ship.x, &app->ship.y, app->ship.vx, app->ship.vy);
  555. update_bullets_position(app);
  556. update_asteroids_position(app);
  557. detect_collisions(app);
  558. /* From time to time, create a new asteroid. The more asteroids
  559. * already on the screen, the smaller probability of creating
  560. * a new one. */
  561. if(app->asteroids_num == 0 || (random() % 5000) < (30 / (1 + app->asteroids_num))) {
  562. add_asteroid(app);
  563. }
  564. app->ticks++;
  565. view_port_update(app->view_port);
  566. }
  567. /* ======================== Flipper specific code =========================== */
  568. bool load_game(AsteroidsApp* app) {
  569. Storage* storage = furi_record_open(RECORD_STORAGE);
  570. File* file = storage_file_alloc(storage);
  571. uint16_t bytes_readed = 0;
  572. if(storage_file_open(file, SAVING_FILENAME, FSAM_READ, FSOM_OPEN_EXISTING)) {
  573. bytes_readed = storage_file_read(file, app, sizeof(AsteroidsApp));
  574. }
  575. storage_file_close(file);
  576. storage_file_free(file);
  577. furi_record_close(RECORD_STORAGE);
  578. return bytes_readed == sizeof(AsteroidsApp);
  579. }
  580. void save_game(AsteroidsApp* app) {
  581. Storage* storage = furi_record_open(RECORD_STORAGE);
  582. if(storage_common_stat(storage, SAVING_DIRECTORY, NULL) == FSE_NOT_EXIST) {
  583. if(!storage_simply_mkdir(storage, SAVING_DIRECTORY)) {
  584. return;
  585. }
  586. }
  587. File* file = storage_file_alloc(storage);
  588. if(storage_file_open(file, SAVING_FILENAME, FSAM_WRITE, FSOM_CREATE_ALWAYS)) {
  589. storage_file_write(file, app, sizeof(AsteroidsApp));
  590. }
  591. storage_file_close(file);
  592. storage_file_free(file);
  593. furi_record_close(RECORD_STORAGE);
  594. }
  595. /* Here all we do is putting the events into the queue that will be handled
  596. * in the while() loop of the app entry point function. */
  597. void input_callback(InputEvent* input_event, void* ctx) {
  598. AsteroidsApp* app = ctx;
  599. furi_message_queue_put(app->event_queue, input_event, FuriWaitForever);
  600. }
  601. /* Allocate the application state and initialize a number of stuff.
  602. * This is called in the entry point to create the application state. */
  603. AsteroidsApp* asteroids_app_alloc() {
  604. AsteroidsApp* app = malloc(sizeof(AsteroidsApp));
  605. load_game(app);
  606. app->gui = furi_record_open(RECORD_GUI);
  607. app->view_port = view_port_alloc();
  608. view_port_draw_callback_set(app->view_port, render_callback, app);
  609. view_port_input_callback_set(app->view_port, input_callback, app);
  610. gui_add_view_port(app->gui, app->view_port, GuiLayerFullscreen);
  611. app->event_queue = furi_message_queue_alloc(8, sizeof(InputEvent));
  612. app->running = 1; /* Turns 0 when back is pressed. */
  613. restart_game_after_gameover(app);
  614. memset(app->pressed, 0, sizeof(app->pressed));
  615. return app;
  616. }
  617. /* Free what the application allocated. It is not clear to me if the
  618. * Flipper OS, once the application exits, will be able to reclaim space
  619. * even if we forget to free something here. */
  620. void asteroids_app_free(AsteroidsApp* app) {
  621. furi_assert(app);
  622. // View related.
  623. view_port_enabled_set(app->view_port, false);
  624. gui_remove_view_port(app->gui, app->view_port);
  625. view_port_free(app->view_port);
  626. furi_record_close(RECORD_GUI);
  627. furi_message_queue_free(app->event_queue);
  628. app->gui = NULL;
  629. free(app);
  630. }
  631. /* Return the time in milliseconds the specified key is continuously
  632. * pressed. Or 0 if it is not pressed. */
  633. uint32_t key_pressed_time(AsteroidsApp* app, InputKey key) {
  634. return app->pressed[key] == 0 ? 0 : furi_get_tick() - app->pressed[key];
  635. }
  636. /* Handle keys interaction. */
  637. void asteroids_update_keypress_state(AsteroidsApp* app, InputEvent input) {
  638. // Allow Rapid fire
  639. if(input.key == InputKeyOk) {
  640. app->fire = true;
  641. }
  642. if(input.type == InputTypePress) {
  643. app->pressed[input.key] = furi_get_tick();
  644. } else if(input.type == InputTypeRelease) {
  645. app->pressed[input.key] = 0;
  646. }
  647. }
  648. int32_t asteroids_app_entry(void* p) {
  649. UNUSED(p);
  650. AsteroidsApp* app = asteroids_app_alloc();
  651. /* Create a timer. We do data analysis in the callback. */
  652. FuriTimer* timer = furi_timer_alloc(game_tick, FuriTimerTypePeriodic, app);
  653. furi_timer_start(timer, furi_kernel_get_tick_frequency() / 10);
  654. /* This is the main event loop: here we get the events that are pushed
  655. * in the queue by input_callback(), and process them one after the
  656. * other. */
  657. InputEvent input;
  658. while(app->running) {
  659. FuriStatus qstat = furi_message_queue_get(app->event_queue, &input, 100);
  660. if(qstat == FuriStatusOk) {
  661. if(DEBUG_MSG)
  662. FURI_LOG_E(TAG, "Main Loop - Input: type %d key %u", input.type, input.key);
  663. /* Handle navigation here. Then handle view-specific inputs
  664. * in the view specific handling function. */
  665. if(input.type == InputTypeShort && input.key == InputKeyBack) {
  666. app->running = 0;
  667. } else {
  668. asteroids_update_keypress_state(app, input);
  669. }
  670. } else {
  671. /* Useful to understand if the app is still alive when it
  672. * does not respond because of bugs. */
  673. if(DEBUG_MSG) {
  674. static int c = 0;
  675. c++;
  676. if(!(c % 20)) FURI_LOG_E(TAG, "Loop timeout");
  677. }
  678. }
  679. }
  680. furi_timer_free(timer);
  681. asteroids_app_free(app);
  682. return 0;
  683. }