app.c 25 KB

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