app.c 37 KB

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