simon_says.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  1. #include <furi.h>
  2. #include <furi_hal.h>
  3. #include <storage/storage.h>
  4. #include <gui/gui.h>
  5. #include <gui/elements.h>
  6. #include <gui/icon.h>
  7. #include <input/input.h>
  8. #include <notification/notification.h>
  9. #include <notification/notification_messages.h>
  10. #include <stdbool.h> // Header-file for boolean data-type.
  11. #include <stdio.h>
  12. #include <string.h>
  13. /* generated by fbt from .png files in images folder */
  14. #include <simon_says_icons.h>
  15. #define TAG "Simon" // Used for logging
  16. #define DEBUG_MSG 1
  17. #define SCREEN_XRES 128
  18. #define SCREEN_YRES 64
  19. #define BOARD_X 72 // Used for board placement
  20. #define BOARD_Y 8
  21. #define GAME_START_LIVES 3
  22. #define SAVING_DIRECTORY "/ext/apps/Games"
  23. #define SAVING_FILENAME SAVING_DIRECTORY "/game_simon_says.save"
  24. // Define Notes
  25. // Shamelessly stolen from Ocarina application
  26. // https://github.com/invalidna-me/flipperzero-ocarina
  27. #define NOTE_UP 587.33f
  28. #define NOTE_LEFT 493.88f
  29. #define NOTE_RIGHT 440.00f
  30. #define NOTE_DOWN 349.23
  31. #define NOTE_OK 293.66f
  32. /* ============================ Data structures ============================= */
  33. typedef enum game_state { preloading, mainMenu, inGame, gameOver, gameVictory } game_state;
  34. typedef enum difficulty_mode { normal, hard } difficulty_mode;
  35. typedef enum shape_names { up, down, left, right, number_of_shapes } Direction;
  36. typedef enum currently_playing { simon, player } currently_playing;
  37. typedef struct {
  38. /* Game state. */
  39. enum game_state gameState; // This is the current game state
  40. bool gameover; /* if true then switch to the game over state */
  41. bool is_wrong_direction; /* Is the last direction wrong? */
  42. enum currently_playing activePlayer; // This is used to track who is playing at the moment
  43. uint32_t lives; /* Number of lives in the current game. */
  44. enum difficulty_mode difficultyMode; // This is the difficulty mode for the current game
  45. bool sound_enabled; // This is the sound enabled flag for the current game
  46. float volume; // This is the volume for the current game
  47. /* Handle Score */
  48. int currentScore; // This is the score for the current
  49. int highScore; /* Highscore. Shown on Game Over Screen */
  50. bool is_new_highscore; /* Is the last score a new highscore? */
  51. /* Handle Shape Display */
  52. uint32_t numberOfMillisecondsBeforeShapeDisappears; // This defines the speed of the game
  53. uint32_t last_shape_displayed_ms; // This is used to time the interval between displaying shapes
  54. enum shape_names simonMoves[1000]; // Store the sequence of shapes that Simon plays
  55. enum shape_names selectedShape; // This is used to track the shape that the player has selected
  56. bool shapeConsumed; // Tracks whether shape has been checked or not
  57. bool set_board_neutral; // This is used to track if the board should be neutral or not
  58. int moveIndex; // This is used to track the current move in the sequence
  59. enum shape_names selected;
  60. enum shape_names board_state; // TODO: This may be redundant by selected
  61. uint32_t last_button_press_tick;
  62. NotificationApp* notification;
  63. } SimonData;
  64. /* ============================== Sequences ============================== */
  65. const NotificationSequence sequence_wrong_move = {
  66. &message_red_255,
  67. &message_vibro_on,
  68. // &message_note_g5, // Play sound but currently disabled
  69. &message_delay_25,
  70. // &message_note_e5,
  71. &message_vibro_off,
  72. &message_sound_off,
  73. NULL,
  74. };
  75. const NotificationSequence sequence_player_submit_move = {
  76. &message_vibro_on,
  77. // &message_note_g5, // Play sound but currently disabled. Need On/Off menu setting
  78. &message_delay_10,
  79. &message_delay_1,
  80. &message_delay_1,
  81. &message_delay_1,
  82. &message_delay_1,
  83. &message_delay_1,
  84. // &message_note_e5,
  85. &message_vibro_off,
  86. &message_sound_off,
  87. NULL,
  88. };
  89. const NotificationSequence sequence_up = {
  90. // &message_vibro_on,
  91. &message_note_g4,
  92. &message_delay_100,
  93. // &message_vibro_off,
  94. &message_sound_off,
  95. NULL,
  96. };
  97. const NotificationSequence sequence_down = {
  98. // &message_vibro_on,
  99. &message_note_c3,
  100. &message_delay_100,
  101. // &message_vibro_off,
  102. &message_sound_off,
  103. NULL,
  104. };
  105. const NotificationSequence sequence_left = {
  106. // &message_vibro_on,
  107. &message_note_e3,
  108. &message_delay_100,
  109. // &message_vibro_off,
  110. &message_sound_off,
  111. NULL,
  112. };
  113. const NotificationSequence sequence_right = {
  114. // &message_vibro_on,
  115. &message_note_g3,
  116. &message_delay_100,
  117. // &message_vibro_off,
  118. &message_sound_off,
  119. NULL,
  120. };
  121. // Indicate that it's Simon's turn
  122. const NotificationSequence sequence_simon_is_playing = {
  123. &message_red_255,
  124. &message_do_not_reset,
  125. NULL,
  126. };
  127. // Indicate that it's the Player's turn
  128. const NotificationSequence sequence_player_is_playing = {
  129. &message_red_0,
  130. &message_do_not_reset,
  131. NULL,
  132. };
  133. const NotificationSequence sequence_cleanup = {
  134. &message_red_0,
  135. &message_green_0,
  136. &message_blue_0,
  137. &message_sound_off,
  138. &message_vibro_off,
  139. NULL,
  140. };
  141. /* ============================ 2D drawing ================================== */
  142. /* Display remaining lives in the center of the board */
  143. void draw_remaining_lives(Canvas* canvas, const SimonData* simon_state) {
  144. // Convert score to string
  145. // int length = snprintf(NULL, 0, "%lu", simon_state->lives);
  146. // char* str_lives_remaining = malloc(length + 1);
  147. // snprintf(str_lives_remaining, length + 1, "%lu", simon_state->lives);
  148. // TODO: Make it a Simon Says icon on top right
  149. canvas_set_color(canvas, ColorBlack);
  150. canvas_set_font(canvas, FontSecondary);
  151. int x = SCREEN_XRES - 6;
  152. int lives = simon_state->lives;
  153. while(lives--) {
  154. canvas_draw_str(canvas, x, 8, "*");
  155. x -= 7;
  156. }
  157. }
  158. void draw_current_score(Canvas* canvas, const SimonData* simon_data) {
  159. /* Draw Game Score. */
  160. canvas_set_color(canvas, ColorXOR);
  161. canvas_set_font(canvas, FontSecondary);
  162. char str_score[32];
  163. snprintf(str_score, sizeof(str_score), "%i", simon_data->currentScore);
  164. canvas_draw_str_aligned(canvas, SCREEN_XRES / 2 + 4, 2, AlignCenter, AlignTop, str_score);
  165. }
  166. /* Main Render Function */
  167. void simon_draw_callback(Canvas* canvas, void* ctx) {
  168. const SimonData* simon_state = acquire_mutex((ValueMutex*)ctx, 25);
  169. if(simon_state == NULL) {
  170. if(DEBUG_MSG) FURI_LOG_E(TAG, "[simon_draw_callback] Null simon state");
  171. return;
  172. }
  173. UNUSED(ctx);
  174. canvas_clear(canvas);
  175. // ######################### Main Menu #########################
  176. // Show Main Menu
  177. if(simon_state->gameState == mainMenu) {
  178. // Draw border frame
  179. canvas_draw_frame(canvas, 1, 1, SCREEN_XRES - 1, SCREEN_YRES - 1); // Border
  180. // Draw Simon text banner
  181. canvas_set_font(canvas, FontSecondary);
  182. canvas_set_color(canvas, ColorBlack);
  183. canvas_draw_str_aligned(
  184. canvas,
  185. SCREEN_XRES / 2,
  186. SCREEN_YRES / 2 - 4,
  187. AlignCenter,
  188. AlignCenter,
  189. "Welcome to Simon Says");
  190. // Display Press OK to start below title
  191. canvas_set_color(canvas, ColorXOR);
  192. canvas_draw_str_aligned(
  193. canvas,
  194. SCREEN_XRES / 2,
  195. SCREEN_YRES / 2 + 10,
  196. AlignCenter,
  197. AlignCenter,
  198. "Press OK to start");
  199. }
  200. // ######################### in Game #########################
  201. //@todo Render Callback
  202. // We're in an active game
  203. if(simon_state->gameState == inGame) {
  204. // Draw Current Score
  205. draw_current_score(canvas, simon_state);
  206. // Draw Lives
  207. draw_remaining_lives(canvas, simon_state);
  208. // Draw Simon Pose
  209. if(simon_state->activePlayer == player) {
  210. // Player's turn
  211. canvas_draw_icon(canvas, 0, 4, &I_DolphinWait_61x59);
  212. } else {
  213. // Simon's turn
  214. canvas_draw_icon(canvas, 0, 4, &I_DolphinTalking_59x63);
  215. }
  216. if(simon_state->set_board_neutral) {
  217. // Draw Neutral Board
  218. canvas_draw_icon(canvas, BOARD_X, BOARD_Y, &I_board); // Draw Board
  219. } else {
  220. switch(simon_state->selectedShape) {
  221. case up:
  222. canvas_draw_icon(canvas, BOARD_X, BOARD_Y, &I_up); // Draw Down
  223. break;
  224. case down:
  225. canvas_draw_icon(canvas, BOARD_X, BOARD_Y, &I_down); // Draw Down
  226. break;
  227. case left:
  228. canvas_draw_icon(canvas, BOARD_X, BOARD_Y, &I_left); // Draw Left
  229. break;
  230. case right:
  231. canvas_draw_icon(canvas, BOARD_X, BOARD_Y, &I_right); // Draw Right
  232. break;
  233. default:
  234. if(DEBUG_MSG)
  235. FURI_LOG_E(
  236. TAG, "Invalid shape: %d", simon_state->simonMoves[simon_state->moveIndex]);
  237. break;
  238. }
  239. }
  240. }
  241. // ######################### Game Over #########################
  242. if(simon_state->gameState == gameOver) {
  243. canvas_set_color(canvas, ColorXOR);
  244. canvas_set_font(canvas, FontPrimary);
  245. // TODO: if new highscore, display blinking "New High Score"
  246. // Display High Score Text
  247. if(simon_state->is_new_highscore) {
  248. canvas_draw_str_aligned(
  249. canvas, SCREEN_XRES / 2, 6, AlignCenter, AlignTop, "New High Score!");
  250. } else {
  251. canvas_draw_str_aligned(
  252. canvas, SCREEN_XRES / 2, 6, AlignCenter, AlignTop, "High Score");
  253. }
  254. // Convert highscore to string
  255. int length = snprintf(NULL, 0, "%i", simon_state->highScore);
  256. char* str_high_score = malloc(length + 1);
  257. snprintf(str_high_score, length + 1, "%i", simon_state->highScore);
  258. // Display High Score
  259. canvas_draw_str_aligned(
  260. canvas, SCREEN_XRES / 2, 22, AlignCenter, AlignCenter, str_high_score);
  261. free(str_high_score);
  262. // Display Game Over
  263. canvas_draw_str_aligned(
  264. canvas, SCREEN_XRES / 2, SCREEN_YRES / 2 + 2, AlignCenter, AlignCenter, "GAME OVER");
  265. // Display Press OK to restart below title
  266. canvas_set_font(canvas, FontSecondary);
  267. canvas_draw_str_aligned(
  268. canvas,
  269. SCREEN_XRES / 2,
  270. SCREEN_YRES / 2 + 15,
  271. AlignCenter,
  272. AlignCenter,
  273. "Press OK to restart");
  274. }
  275. // ######################### Victory #########################
  276. //Player Beat Simon beyond limit! A word record holder here!
  277. //TODO
  278. //release the mutex
  279. release_mutex((ValueMutex*)ctx, simon_state);
  280. }
  281. /* ======================== Input Handling ============================== */
  282. void simon_input_callback(InputEvent* input_event, void* ctx) {
  283. furi_assert(ctx);
  284. FuriMessageQueue* event_queue = ctx;
  285. furi_message_queue_put(event_queue, input_event, FuriWaitForever);
  286. }
  287. /* ======================== Simon Game Engine ======================== */
  288. bool load_game(SimonData* app) {
  289. Storage* storage = furi_record_open(RECORD_STORAGE);
  290. File* file = storage_file_alloc(storage);
  291. uint16_t bytes_readed = 0;
  292. if(storage_file_open(file, SAVING_FILENAME, FSAM_READ, FSOM_OPEN_EXISTING)) {
  293. bytes_readed = storage_file_read(file, app, sizeof(SimonData));
  294. }
  295. storage_file_close(file);
  296. storage_file_free(file);
  297. furi_record_close(RECORD_STORAGE);
  298. return bytes_readed == sizeof(SimonData);
  299. }
  300. void save_game(SimonData* app) {
  301. Storage* storage = furi_record_open(RECORD_STORAGE);
  302. if(storage_common_stat(storage, SAVING_DIRECTORY, NULL) == FSE_NOT_EXIST) {
  303. if(!storage_simply_mkdir(storage, SAVING_DIRECTORY)) {
  304. return;
  305. }
  306. }
  307. File* file = storage_file_alloc(storage);
  308. if(storage_file_open(file, SAVING_FILENAME, FSAM_WRITE, FSOM_CREATE_ALWAYS)) {
  309. storage_file_write(file, app, sizeof(SimonData));
  310. }
  311. storage_file_close(file);
  312. storage_file_free(file);
  313. furi_record_close(RECORD_STORAGE);
  314. }
  315. int getRandomIntInRange(int lower, int upper) {
  316. return (rand() % (upper - lower + 1)) + lower;
  317. }
  318. void play_sound_sequence_correct() {
  319. notification_message(furi_record_open(RECORD_NOTIFICATION), &sequence_success);
  320. }
  321. void play_sound_wrong_move() {
  322. //TODO: play wrong sound: Try sequence_audiovisual_alert
  323. notification_message(furi_record_open(RECORD_NOTIFICATION), &sequence_error);
  324. }
  325. /* Restart game and give player a chance to try again on same sequence */
  326. // @todo restartGame
  327. void resetGame(SimonData* app) {
  328. app->moveIndex = 0;
  329. app->numberOfMillisecondsBeforeShapeDisappears = 500;
  330. app->activePlayer = simon;
  331. app->is_wrong_direction = false;
  332. app->last_button_press_tick = 0;
  333. app->set_board_neutral = true;
  334. app->activePlayer = simon;
  335. }
  336. /* Set gameover state */
  337. void game_over(SimonData* app) {
  338. if(app->is_new_highscore) save_game(app); // Save highscore but only on change
  339. app->gameover = true;
  340. app->lives = GAME_START_LIVES; // Show 3 lives in game over screen to match new game start
  341. app->gameState = gameOver;
  342. }
  343. /* Called after gameover to restart the game. This function
  344. * also calls restart_game(). */
  345. void restart_game_after_gameover(SimonData* app) {
  346. app->volume = 1.0f; //TODO: make this a setting
  347. app->gameState = inGame;
  348. app->gameover = false;
  349. app->currentScore = 0;
  350. app->is_new_highscore = false;
  351. app->lives = GAME_START_LIVES;
  352. app->simonMoves[0] = rand() % number_of_shapes;
  353. resetGame(app);
  354. }
  355. void addNewSimonMove(int addAtIndex, SimonData* app) {
  356. app->simonMoves[addAtIndex] = getRandomIntInRange(0, 3);
  357. }
  358. void startNewRound(SimonData* app) {
  359. addNewSimonMove(app->currentScore, app);
  360. app->moveIndex = 0;
  361. app->activePlayer = simon;
  362. }
  363. void onPlayerAnsweredCorrect(SimonData* app) {
  364. app->moveIndex++;
  365. }
  366. void onPlayerAnsweredWrong(SimonData* app) {
  367. if(app->lives > 0) {
  368. app->lives--;
  369. // Play the wrong sound
  370. if(app->sound_enabled) {
  371. play_sound_wrong_move();
  372. }
  373. resetGame(app);
  374. } else {
  375. // The player has no lives left
  376. // Game over
  377. game_over(app);
  378. //TODO: Play unique game over sound
  379. }
  380. }
  381. bool isRoundComplete(SimonData* app) {
  382. return app->moveIndex == app->currentScore;
  383. }
  384. enum shape_names getCurrentSimonMove(SimonData* app) {
  385. return app->simonMoves[app->moveIndex];
  386. }
  387. void onPlayerSelectedShapeCallback(enum shape_names shape, SimonData* app) {
  388. if(furi_hal_speaker_is_mine() || furi_hal_speaker_acquire(30)) {
  389. furi_hal_speaker_start(NOTE_UP, app->volume);
  390. }
  391. if(shape == getCurrentSimonMove(app)) {
  392. onPlayerAnsweredCorrect(app);
  393. } else {
  394. onPlayerAnsweredWrong(app);
  395. }
  396. }
  397. //@todo gametick
  398. void game_tick(SimonData* simon_state) {
  399. if(simon_state->gameState == inGame) {
  400. if(simon_state->activePlayer == simon) {
  401. // ############### Simon Turn ###############
  402. notification_message(simon_state->notification, &sequence_simon_is_playing);
  403. //@todo Gameplay
  404. if(simon_state->set_board_neutral) {
  405. if(simon_state->moveIndex < simon_state->currentScore) {
  406. simon_state->selectedShape = getCurrentSimonMove(simon_state);
  407. simon_state->set_board_neutral = false;
  408. simon_state->moveIndex++;
  409. } else {
  410. simon_state->activePlayer = player;
  411. simon_state->set_board_neutral = true;
  412. simon_state->moveIndex = 0;
  413. }
  414. } else {
  415. simon_state->set_board_neutral = true;
  416. }
  417. } else {
  418. // ############### Player Turn ###############
  419. notification_message(simon_state->notification, &sequence_player_is_playing);
  420. // It's Player's Turn
  421. if(isRoundComplete(simon_state)) {
  422. simon_state->activePlayer = simon;
  423. simon_state->currentScore++;
  424. // app->numberOfMillisecondsBeforeShapeDisappears -= 50;
  425. //TODO: Hacky way of handling highscore by subtracting 1 to account for the first move
  426. if(simon_state->currentScore - 1 > simon_state->highScore) {
  427. simon_state->highScore = simon_state->currentScore - 1;
  428. simon_state->is_new_highscore = true;
  429. }
  430. if(simon_state->sound_enabled) {
  431. play_sound_sequence_correct();
  432. }
  433. startNewRound(simon_state);
  434. }
  435. }
  436. }
  437. }
  438. /* ======================== Main Entry Point ============================== */
  439. int32_t simon_says_app_entry(void* p) {
  440. UNUSED(p);
  441. FuriMessageQueue* event_queue = furi_message_queue_alloc(8, sizeof(InputEvent));
  442. SimonData* simon_state = malloc(sizeof(SimonData));
  443. ValueMutex simon_state_value_mutex;
  444. if(!init_mutex(&simon_state_value_mutex, simon_state, sizeof(SimonData))) {
  445. FURI_LOG_E(TAG, "cannot create mutex\r\n");
  446. free(simon_state);
  447. return -1;
  448. }
  449. // Configure view port
  450. ViewPort* view_port = view_port_alloc();
  451. view_port_draw_callback_set(view_port, simon_draw_callback, &simon_state_value_mutex);
  452. view_port_input_callback_set(view_port, simon_input_callback, event_queue);
  453. // Register view port in GUI
  454. Gui* gui = furi_record_open(RECORD_GUI);
  455. gui_add_view_port(gui, view_port, GuiLayerFullscreen);
  456. NotificationApp* notification = furi_record_open(RECORD_NOTIFICATION);
  457. simon_state->notification = notification;
  458. InputEvent input;
  459. // Show Main Menu Screen
  460. //TODO: Disable Loading game for debugging
  461. load_game(simon_state);
  462. simon_state->gameState = mainMenu;
  463. while(true) {
  464. game_tick(simon_state);
  465. FuriStatus q_status = furi_message_queue_get(
  466. event_queue, &input, simon_state->numberOfMillisecondsBeforeShapeDisappears);
  467. if(q_status == FuriStatusOk) {
  468. FURI_LOG_D(TAG, "Got input event: %d", input.key);
  469. //break out of the loop if the back key is pressed
  470. if(input.key == InputKeyBack && input.type == InputTypeLong) {
  471. // Save high score before quitting
  472. if(simon_state->is_new_highscore) {
  473. save_game(simon_state);
  474. }
  475. break;
  476. }
  477. if(input.type == InputTypeLong) {
  478. // Do Nothing. Ignore long press events
  479. }
  480. //@todo Set Game States
  481. if(input.key == InputKeyOk && simon_state->gameState != inGame) {
  482. restart_game_after_gameover(simon_state);
  483. // Set Simon Board state
  484. startNewRound(simon_state);
  485. view_port_update(view_port);
  486. }
  487. // Keep LED on if it is Simon's turn
  488. if(simon_state->activePlayer == player) {
  489. notification_message(notification, &sequence_player_is_playing);
  490. if(input.type == InputTypePress) {
  491. simon_state->set_board_neutral = false;
  492. switch(input.key) {
  493. case InputKeyUp:
  494. simon_state->selectedShape = up;
  495. onPlayerSelectedShapeCallback(up, simon_state);
  496. break;
  497. case InputKeyDown:
  498. simon_state->selectedShape = down;
  499. onPlayerSelectedShapeCallback(down, simon_state);
  500. break;
  501. case InputKeyLeft:
  502. simon_state->selectedShape = left;
  503. onPlayerSelectedShapeCallback(left, simon_state);
  504. break;
  505. case InputKeyRight:
  506. simon_state->selectedShape = right;
  507. onPlayerSelectedShapeCallback(right, simon_state);
  508. break;
  509. default:
  510. break;
  511. }
  512. } else {
  513. FURI_LOG_D(TAG, "Input type is not short");
  514. simon_state->set_board_neutral = true;
  515. }
  516. }
  517. } else {
  518. FURI_LOG_E(TAG, "cannot get message from queue\r\n");
  519. }
  520. // @todo Animation Loop for debug
  521. // if(simon_state->gameState == inGame && simon_state->activePlayer == simon) {
  522. // simon_state->currentScore++;
  523. // simon_state->set_board_neutral = !simon_state->set_board_neutral;
  524. // }
  525. view_port_update(view_port);
  526. }
  527. notification_message(notification, &sequence_cleanup);
  528. gui_remove_view_port(gui, view_port);
  529. view_port_free(view_port);
  530. furi_message_queue_free(event_queue);
  531. free(simon_state);
  532. furi_record_close(RECORD_NOTIFICATION);
  533. furi_record_close(RECORD_GUI);
  534. return 0;
  535. }