simon_says.c 20 KB

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