app.c 36 KB

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