app.c 36 KB

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