app.c 44 KB

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