app.c 37 KB

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