player.c 20 KB

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