player.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641
  1. #include <game/player.h>
  2. #include <game/icon.h>
  3. #include <game/storage.h>
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <math.h>
  7. #include <engine/entity_i.h>
  8. /****** Entities: Player ******/
  9. static Level *player_next_level(GameManager *manager)
  10. {
  11. GameContext *game_context = game_manager_game_context_get(manager);
  12. if (!game_context)
  13. {
  14. FURI_LOG_E(TAG, "Failed to get game context");
  15. return NULL;
  16. }
  17. int next_index = game_context->current_level + 1;
  18. if (next_index >= game_context->level_count)
  19. {
  20. FURI_LOG_E(TAG, "No more levels to load (index %d)", next_index);
  21. return game_context->levels[0];
  22. }
  23. // Allocate the level if it hasn't been loaded yet
  24. if (!game_context->levels[next_index])
  25. {
  26. if (!allocate_level(manager, next_index))
  27. {
  28. FURI_LOG_E(TAG, "Failed to allocate level %d", next_index);
  29. return NULL;
  30. }
  31. }
  32. // Update current level and return it
  33. game_context->current_level = next_index;
  34. return game_context->levels[next_index];
  35. }
  36. // Update player stats based on XP using iterative method
  37. int player_level_iterative_get(uint32_t xp)
  38. {
  39. int level = 1;
  40. uint32_t xp_required = 100; // Base XP for level 2
  41. while (level < 100 && xp >= xp_required) // Maximum level supported
  42. {
  43. level++;
  44. xp_required = (uint32_t)(xp_required * 1.5); // 1.5 growth factor per level
  45. }
  46. return level;
  47. }
  48. // Fetch last_response once then store it in ws_info to parse later
  49. static void player_ws_info_update(GameManager *manager)
  50. {
  51. GameContext *game_context = game_manager_game_context_get(manager);
  52. if (!game_context || !game_context->fhttp)
  53. {
  54. FURI_LOG_E(TAG, "Failed to get game context or FlipperHTTP");
  55. return;
  56. }
  57. if (!game_context->ws_info || !game_context->fhttp->last_response)
  58. {
  59. return;
  60. }
  61. // validate response
  62. if (strlen(game_context->fhttp->last_response) > 0)
  63. {
  64. furi_string_set_str(game_context->ws_info, game_context->fhttp->last_response);
  65. }
  66. }
  67. void player_spawn(Level *level, GameManager *manager)
  68. {
  69. if (!level || !manager)
  70. {
  71. FURI_LOG_E(TAG, "Invalid arguments to player_spawn");
  72. return;
  73. }
  74. GameContext *game_context = game_manager_game_context_get(manager);
  75. if (!game_context)
  76. {
  77. FURI_LOG_E(TAG, "Failed to get game context");
  78. return;
  79. }
  80. game_context->player = level_add_entity(level, &player_desc);
  81. if (!game_context->player)
  82. {
  83. FURI_LOG_E(TAG, "Failed to add player entity to level");
  84. return;
  85. }
  86. // Set player position.
  87. entity_pos_set(game_context->player, (Vector){WORLD_WIDTH / 2, WORLD_HEIGHT / 2});
  88. // Get player context
  89. PlayerContext *pctx = entity_context_get(game_context->player);
  90. if (!pctx)
  91. {
  92. FURI_LOG_E(TAG, "Failed to get player context");
  93. return;
  94. }
  95. SpriteContext *sprite_context = sprite_context_get(player_sprite_choices[player_sprite_index]);
  96. if (!sprite_context)
  97. {
  98. FURI_LOG_E(TAG, "Failed to get sprite context");
  99. return;
  100. }
  101. // add a collider to the player entity
  102. entity_collider_add_rect(game_context->player, sprite_context->width, sprite_context->height);
  103. // player context must be set each level or NULL pointer will be dereferenced
  104. if (!load_player_context(pctx))
  105. {
  106. FURI_LOG_E(TAG, "Loading player context failed. Initializing default values.");
  107. // Initialize default player context
  108. pctx->sprite_right = game_manager_sprite_load(manager, sprite_context->right_file_name);
  109. pctx->sprite_left = game_manager_sprite_load(manager, sprite_context->left_file_name);
  110. pctx->direction = ENTITY_RIGHT; // default direction
  111. pctx->left = false; // default sprite direction
  112. pctx->health = 100;
  113. pctx->strength = 10;
  114. pctx->level = 1;
  115. pctx->xp = 0;
  116. pctx->start_position = entity_pos_get(game_context->player);
  117. pctx->attack_timer = 0.1f;
  118. pctx->elapsed_attack_timer = pctx->attack_timer;
  119. pctx->health_regen = 1; // 1 health per second
  120. pctx->elapsed_health_regen = 0;
  121. pctx->max_health = 100 + ((pctx->level - 1) * 10); // 10 health per level
  122. // level 10 level required for PvP
  123. if (game_context->game_mode == GAME_MODE_PVP)
  124. {
  125. FURI_LOG_E(TAG, "Player level is not high enough for PvP");
  126. game_context->end_reason = GAME_END_PVP_REQUIREMENT;
  127. game_context->ended_early = true;
  128. }
  129. // Set player username
  130. if (!load_char("Flip-Social-Username", pctx->username, sizeof(pctx->username)))
  131. {
  132. // check if data/player/username
  133. if (!load_char("player/username", pctx->username, sizeof(pctx->username)))
  134. {
  135. // If loading username fails, default to "Player"
  136. snprintf(pctx->username, sizeof(pctx->username), "Player");
  137. }
  138. }
  139. // Save the initialized context
  140. if (!save_player_context(pctx))
  141. {
  142. FURI_LOG_E(TAG, "Failed to save player context after initialization");
  143. }
  144. free(sprite_context);
  145. return;
  146. }
  147. // Load player sprite
  148. pctx->sprite_right = game_manager_sprite_load(manager, sprite_context->right_file_name);
  149. pctx->sprite_left = game_manager_sprite_load(manager, sprite_context->left_file_name);
  150. pctx->start_position = entity_pos_get(game_context->player);
  151. // Determine the player's level based on XP
  152. pctx->level = player_level_iterative_get(pctx->xp);
  153. // level 10 level required for PvP
  154. if (game_context->game_mode == GAME_MODE_PVP && pctx->level < 10)
  155. {
  156. FURI_LOG_E(TAG, "Player level %ld is not high enough for PvP", pctx->level);
  157. game_context->end_reason = GAME_END_PVP_REQUIREMENT;
  158. game_context->ended_early = true;
  159. }
  160. // Update strength and max health based on the new level
  161. pctx->strength = 10 + (pctx->level * 1); // 1 strength per level
  162. pctx->max_health = 100 + ((pctx->level - 1) * 10); // 10 health per level
  163. // set the player's left sprite direction
  164. pctx->left = pctx->direction == ENTITY_LEFT ? true : false;
  165. free(sprite_context);
  166. }
  167. static int player_vgm_increase(float value, float increase)
  168. {
  169. const int val = abs((int)(round(value + increase) / 2));
  170. return val < 1 ? 1 : val;
  171. }
  172. static void player_vgm_direction(Imu *imu, PlayerContext *player, Vector *pos)
  173. {
  174. const float pitch = -imu_pitch_get(imu);
  175. const float roll = -imu_roll_get(imu);
  176. const float min_x = atof_(vgm_levels[vgm_x_index]) + 5.0; // minimum of 3
  177. const float min_y = atof_(vgm_levels[vgm_y_index]) + 5.0; // minimum of 3
  178. if (pitch > min_x)
  179. {
  180. pos->x += player_vgm_increase(pitch, min_x);
  181. player->dx = 1;
  182. player->direction = ENTITY_RIGHT;
  183. }
  184. else if (pitch < -min_x)
  185. {
  186. pos->x += -player_vgm_increase(pitch, min_x);
  187. player->dx = -1;
  188. player->direction = ENTITY_LEFT;
  189. }
  190. if (roll > min_y)
  191. {
  192. pos->y += player_vgm_increase(roll, min_y);
  193. player->dy = 1;
  194. player->direction = ENTITY_DOWN;
  195. }
  196. else if (roll < -min_y)
  197. {
  198. pos->y += -player_vgm_increase(roll, min_y);
  199. player->dy = -1;
  200. player->direction = ENTITY_UP;
  201. }
  202. }
  203. // This static function handles collisions with icons.
  204. // It receives the player entity pointer, the player's current position, and a pointer to PlayerContext.
  205. static void player_handle_collision(Entity *playerEntity, Vector playerPos, PlayerContext *player)
  206. {
  207. // If there is no active icon group, do nothing.
  208. if (!g_current_icon_group)
  209. return;
  210. // Loop over all icon specifications in the current icon group.
  211. for (int i = 0; i < g_current_icon_group->count; i++)
  212. {
  213. IconSpec *spec = &g_current_icon_group->icons[i];
  214. // Calculate the difference between player's position and the icon's center.
  215. float dx = playerPos.x - spec->pos.x;
  216. float dy = playerPos.y - spec->pos.y;
  217. // Use an approximate collision radius:
  218. float radius = (spec->size.x + spec->size.y) / 4.0f;
  219. // Collision: if player's distance to the icon center is less than the collision radius.
  220. if ((dx * dx + dy * dy) < (radius * radius))
  221. {
  222. // Revert the player's position and reset movement.
  223. entity_pos_set(playerEntity, player->old_position);
  224. player->dx = 0;
  225. player->dy = 0;
  226. break;
  227. }
  228. }
  229. }
  230. uint16_t elapsed_ws_timer = 0;
  231. static void player_update(Entity *self, GameManager *manager, void *context)
  232. {
  233. if (!self || !manager || !context)
  234. return;
  235. PlayerContext *player = (PlayerContext *)context;
  236. InputState input = game_manager_input_get(manager);
  237. Vector pos = entity_pos_get(self);
  238. GameContext *game_context = game_manager_game_context_get(manager);
  239. // ensure game is stopped
  240. if (game_context->ended_early)
  241. {
  242. game_manager_game_stop(manager);
  243. return;
  244. }
  245. // update websocket player context
  246. if (game_context->game_mode == GAME_MODE_PVP)
  247. {
  248. // load the websocket info
  249. player_ws_info_update(manager);
  250. // if pvp, end the game if the player is dead
  251. if (player->health <= 0)
  252. {
  253. player->health = player->max_health;
  254. save_player_context(player);
  255. furi_delay_ms(100);
  256. game_manager_game_stop(manager);
  257. return;
  258. }
  259. if (player->old_position.x != pos.x || player->old_position.y != pos.y)
  260. {
  261. elapsed_ws_timer++;
  262. // only send the websocket update every 200ms
  263. if (elapsed_ws_timer >= (game_context->fps / 5))
  264. {
  265. if (game_context->fhttp)
  266. {
  267. player->start_position = player->old_position;
  268. websocket_player_context(player, game_context->fhttp);
  269. }
  270. elapsed_ws_timer = 0;
  271. }
  272. }
  273. }
  274. player->old_position = pos;
  275. // Determine the player's level based on XP
  276. player->level = player_level_iterative_get(player->xp);
  277. player->strength = 10 + (player->level * 1); // 1 strength per level
  278. player->max_health = 100 + ((player->level - 1) * 10); // 10 health per level
  279. // Store previous direction
  280. int prev_dx = player->dx;
  281. int prev_dy = player->dy;
  282. // Reset movement deltas each frame
  283. player->dx = 0;
  284. player->dy = 0;
  285. if (game_context->imu_present)
  286. {
  287. // update position using the IMU
  288. player_vgm_direction(game_context->imu, player, &pos);
  289. }
  290. // Apply health regeneration
  291. player->elapsed_health_regen += 1.0f / game_context->fps;
  292. if (player->elapsed_health_regen >= 1.0f && player->health < player->max_health)
  293. {
  294. player->health += (player->health_regen + player->health > player->max_health)
  295. ? (player->max_health - player->health)
  296. : player->health_regen;
  297. player->elapsed_health_regen = 0;
  298. }
  299. // Increment the elapsed_attack_timer for the player
  300. player->elapsed_attack_timer += 1.0f / game_context->fps;
  301. // Handle movement input
  302. if (input.held & GameKeyUp)
  303. {
  304. if (game_context->last_button == GameKeyUp)
  305. game_context->elapsed_button_timer += 1;
  306. else
  307. game_context->elapsed_button_timer = 0;
  308. if (!game_context->is_menu_open)
  309. {
  310. pos.y -= (1 + game_context->icon_offset);
  311. player->dy = -1;
  312. player->direction = ENTITY_UP;
  313. }
  314. else
  315. {
  316. // next menu view
  317. // we can only go up to info from settings
  318. game_context->menu_screen = GAME_MENU_INFO;
  319. }
  320. game_context->last_button = GameKeyUp;
  321. }
  322. if (input.held & GameKeyDown)
  323. {
  324. if (game_context->last_button == GameKeyDown)
  325. game_context->elapsed_button_timer += 1;
  326. else
  327. game_context->elapsed_button_timer = 0;
  328. if (!game_context->is_menu_open)
  329. {
  330. pos.y += (1 + game_context->icon_offset);
  331. player->dy = 1;
  332. player->direction = ENTITY_DOWN;
  333. }
  334. else
  335. {
  336. // next menu view
  337. // we can only go down to more from info
  338. game_context->menu_screen = GAME_MENU_MORE;
  339. }
  340. game_context->last_button = GameKeyDown;
  341. }
  342. if (input.held & GameKeyLeft)
  343. {
  344. if (game_context->last_button == GameKeyLeft)
  345. game_context->elapsed_button_timer += 1;
  346. else
  347. game_context->elapsed_button_timer = 0;
  348. if (!game_context->is_menu_open)
  349. {
  350. pos.x -= (1 + game_context->icon_offset);
  351. player->dx = -1;
  352. player->direction = ENTITY_LEFT;
  353. }
  354. else
  355. {
  356. // if the menu is open, move the selection left
  357. if (game_context->menu_selection < 1)
  358. {
  359. game_context->menu_selection += 1;
  360. }
  361. }
  362. game_context->last_button = GameKeyLeft;
  363. }
  364. if (input.held & GameKeyRight)
  365. {
  366. if (game_context->last_button == GameKeyRight)
  367. game_context->elapsed_button_timer += 1;
  368. else
  369. game_context->elapsed_button_timer = 0;
  370. if (!game_context->is_menu_open)
  371. {
  372. pos.x += (1 + game_context->icon_offset);
  373. player->dx = 1;
  374. player->direction = ENTITY_RIGHT;
  375. }
  376. else
  377. {
  378. // if the menu is open, move the selection right
  379. if (game_context->menu_selection < 1)
  380. {
  381. game_context->menu_selection += 1;
  382. }
  383. }
  384. game_context->last_button = GameKeyRight;
  385. }
  386. if (input.held & GameKeyOk)
  387. {
  388. if (game_context->last_button == GameKeyOk)
  389. game_context->elapsed_button_timer += 1;
  390. else
  391. game_context->elapsed_button_timer = 0;
  392. game_context->last_button = GameKeyOk;
  393. // if all enemies are dead, allow the "OK" button to switch levels
  394. // otherwise the "OK" button will be used to attack
  395. if (game_context->game_mode != GAME_MODE_PVP && game_context->enemy_count == 0 && !game_context->is_switching_level)
  396. {
  397. game_context->is_switching_level = true;
  398. save_player_context(player);
  399. furi_delay_ms(100);
  400. game_manager_next_level_set(manager, player_next_level(manager));
  401. return;
  402. }
  403. // if the OK button is held for 1 seconds,show the menu
  404. if (game_context->elapsed_button_timer > (1 * game_context->fps))
  405. {
  406. // open up menu on the INFO screen
  407. game_context->menu_screen = GAME_MENU_INFO;
  408. game_context->menu_selection = 0;
  409. game_context->is_menu_open = true;
  410. }
  411. }
  412. if (input.held & GameKeyBack)
  413. {
  414. if (game_context->last_button == GameKeyBack)
  415. game_context->elapsed_button_timer += 1;
  416. else
  417. game_context->elapsed_button_timer = 0;
  418. game_context->last_button = GameKeyBack;
  419. if (game_context->is_menu_open)
  420. {
  421. game_context->is_menu_open = false;
  422. }
  423. // if the back button is held for 1 seconds, stop the game
  424. if (game_context->elapsed_button_timer > (1 * game_context->fps))
  425. {
  426. if (!game_context->is_menu_open)
  427. {
  428. save_player_context(player);
  429. furi_delay_ms(100);
  430. game_manager_game_stop(manager);
  431. return;
  432. }
  433. }
  434. }
  435. // adjust tutorial step
  436. if (game_context->game_mode == GAME_MODE_STORY)
  437. {
  438. story_update(self, manager);
  439. }
  440. // Clamp the player's position to stay within world bounds
  441. pos.x = CLAMP(pos.x, WORLD_WIDTH - 5, 5);
  442. pos.y = CLAMP(pos.y, WORLD_HEIGHT - 5, 5);
  443. // Update player position
  444. entity_pos_set(self, pos);
  445. // If the player is not moving, retain the last movement direction
  446. if (player->dx == 0 && player->dy == 0)
  447. {
  448. player->dx = prev_dx;
  449. player->dy = prev_dy;
  450. player->state = ENTITY_IDLE;
  451. }
  452. else
  453. player->state = ENTITY_MOVING;
  454. // handle icon collision
  455. player_handle_collision(self, pos, player);
  456. }
  457. static void player_render(Entity *self, GameManager *manager, Canvas *canvas, void *context)
  458. {
  459. if (!self || !context || !canvas || !manager)
  460. return;
  461. // Get game context
  462. GameContext *game_context = game_manager_game_context_get(manager);
  463. // Get player context
  464. PlayerContext *player = context;
  465. // Get player position
  466. Vector pos = entity_pos_get(self);
  467. // Calculate camera offset to center the player
  468. draw_camera_x = pos.x - (SCREEN_WIDTH / 2);
  469. draw_camera_y = pos.y - (SCREEN_HEIGHT / 2);
  470. // Clamp camera position to prevent showing areas outside the world
  471. draw_camera_x = CLAMP(draw_camera_x, WORLD_WIDTH - SCREEN_WIDTH, 0);
  472. draw_camera_y = CLAMP(draw_camera_y, WORLD_HEIGHT - SCREEN_HEIGHT, 0);
  473. // if player is moving right or left, draw the corresponding sprite
  474. if (player->direction == ENTITY_RIGHT || player->direction == ENTITY_LEFT)
  475. {
  476. canvas_draw_sprite(
  477. canvas,
  478. player->direction == ENTITY_RIGHT ? player->sprite_right : player->sprite_left,
  479. pos.x - draw_camera_x - 5, // Center the sprite horizontally
  480. pos.y - draw_camera_y - 5 // Center the sprite vertically
  481. );
  482. player->left = false;
  483. }
  484. else // otherwise
  485. {
  486. // Default to last sprite direction
  487. canvas_draw_sprite(
  488. canvas,
  489. player->left ? player->sprite_left : player->sprite_right,
  490. pos.x - draw_camera_x - 5, // Center the sprite horizontally
  491. pos.y - draw_camera_y - 5 // Center the sprite vertically
  492. );
  493. }
  494. // Draw the outer bounds adjusted by camera offset
  495. canvas_draw_frame(canvas, -draw_camera_x, -draw_camera_y, WORLD_WIDTH, WORLD_HEIGHT);
  496. // render tutorial
  497. if (game_context->game_mode == GAME_MODE_STORY)
  498. {
  499. story_draw(self, canvas, manager);
  500. }
  501. else
  502. {
  503. // render background
  504. draw_background_render(canvas, manager);
  505. }
  506. }
  507. const EntityDescription player_desc = {
  508. .start = NULL, // called when entity is added to the level
  509. .stop = NULL, // called when entity is removed from the level
  510. .update = player_update, // called every frame
  511. .render = player_render, // called every frame, after update
  512. .collision = NULL, // called when entity collides with another entity
  513. .event = NULL, // called when entity receives an event
  514. .context_size = sizeof(PlayerContext), // size of entity context, will be automatically allocated and freed
  515. };
  516. static SpriteContext *sprite_generic_alloc(SpriteID id, const char *char_id, const char *type, uint8_t width, uint8_t height)
  517. {
  518. SpriteContext *ctx = malloc(sizeof(SpriteContext));
  519. if (!ctx)
  520. {
  521. FURI_LOG_E("Game", "Failed to allocate SpriteContext");
  522. return NULL;
  523. }
  524. ctx->id = id;
  525. ctx->width = width;
  526. ctx->height = height;
  527. if (is_str(type, "player"))
  528. {
  529. snprintf(ctx->right_file_name, sizeof(ctx->right_file_name), "player_right_%s_%dx%dpx.fxbm", char_id, width, height);
  530. snprintf(ctx->left_file_name, sizeof(ctx->left_file_name), "player_left_%s_%dx%dpx.fxbm", char_id, width, height);
  531. }
  532. else if (is_str(type, "enemy"))
  533. {
  534. snprintf(ctx->right_file_name, sizeof(ctx->right_file_name), "enemy_right_%s_%dx%dpx.fxbm", char_id, width, height);
  535. snprintf(ctx->left_file_name, sizeof(ctx->left_file_name), "enemy_left_%s_%dx%dpx.fxbm", char_id, width, height);
  536. }
  537. else if (is_str(type, "npc"))
  538. {
  539. snprintf(ctx->right_file_name, sizeof(ctx->right_file_name), "npc_right_%s_%dx%dpx.fxbm", char_id, width, height);
  540. snprintf(ctx->left_file_name, sizeof(ctx->left_file_name), "npc_left_%s_%dx%dpx.fxbm", char_id, width, height);
  541. }
  542. return ctx;
  543. }
  544. SpriteContext *sprite_context_get(const char *name)
  545. {
  546. if (is_str(name, "axe"))
  547. return sprite_generic_alloc(SPRITE_ID_AXE, "axe", "player", 15, 11);
  548. else if (is_str(name, "bow"))
  549. return sprite_generic_alloc(SPRITE_ID_BOW, "bow", "player", 13, 11);
  550. else if (is_str(name, "naked"))
  551. return sprite_generic_alloc(SPRITE_ID_NAKED, "naked", "player", 10, 10);
  552. else if (is_str(name, "sword"))
  553. return sprite_generic_alloc(SPRITE_ID_SWORD, "sword", "player", 15, 11);
  554. //
  555. else if (is_str(name, "cyclops"))
  556. return sprite_generic_alloc(SPRITE_ID_CYCLOPS, "cyclops", "enemy", 10, 11);
  557. else if (is_str(name, "ghost"))
  558. return sprite_generic_alloc(SPRITE_ID_GHOST, "ghost", "enemy", 15, 15);
  559. else if (is_str(name, "ogre"))
  560. return sprite_generic_alloc(SPRITE_ID_OGRE, "ogre", "enemy", 10, 13);
  561. //
  562. else if (is_str(name, "funny"))
  563. return sprite_generic_alloc(SPRITE_ID_FUNNY, "funny", "npc", 15, 21);
  564. // If no match is found
  565. FURI_LOG_E("Game", "Sprite not found: %s", name);
  566. return NULL;
  567. }