game_2048.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. /*
  2. * Copyright 2022 Eugene Kirzhanov
  3. * Use of this source code is governed by an MIT-style
  4. * license that can be found in the LICENSE file or at
  5. * https://opensource.org/licenses/MIT
  6. *
  7. * Thanks to:
  8. * - DroomOne: https://github.com/DroomOne/flipperzero-firmware
  9. * - x27: https://github.com/x27/flipperzero-game15
  10. */
  11. #include <furi.h>
  12. #include <gui/gui.h>
  13. #include <input/input.h>
  14. #include <storage/storage.h>
  15. #include <dolphin/dolphin.h>
  16. #include "digits.h"
  17. #include "array_utils.h"
  18. #define CELLS_COUNT 4
  19. #define CELL_INNER_SIZE 14
  20. #define FRAME_LEFT 10
  21. #define FRAME_TOP 1
  22. #define FRAME_SIZE 61
  23. #define SAVING_DIRECTORY STORAGE_APP_DATA_PATH_PREFIX
  24. #define SAVING_FILENAME SAVING_DIRECTORY "/game_2048.save"
  25. typedef enum {
  26. GameStateMenu,
  27. GameStateInProgress,
  28. GameStateGameOver,
  29. } State;
  30. typedef struct {
  31. FuriMutex* mutex;
  32. State state;
  33. uint8_t table[CELLS_COUNT][CELLS_COUNT];
  34. uint32_t score;
  35. uint32_t moves;
  36. int8_t selected_menu_item;
  37. uint32_t top_score;
  38. } GameState;
  39. typedef struct {
  40. uint32_t points;
  41. bool is_table_updated;
  42. } MoveResult;
  43. #define MENU_ITEMS_COUNT 2
  44. static const char* popup_menu_strings[] = {"Resume", "New Game"};
  45. static void input_callback(InputEvent* input_event, void* ctx) {
  46. furi_assert(ctx);
  47. FuriMessageQueue* event_queue = ctx;
  48. furi_message_queue_put(event_queue, input_event, FuriWaitForever);
  49. }
  50. static void draw_frame(Canvas* canvas) {
  51. canvas_draw_frame(canvas, FRAME_LEFT, FRAME_TOP, FRAME_SIZE, FRAME_SIZE);
  52. uint8_t offs = FRAME_LEFT + CELL_INNER_SIZE + 1;
  53. for(uint8_t i = 0; i < CELLS_COUNT - 1; i++) {
  54. canvas_draw_line(canvas, offs, FRAME_TOP + 1, offs, FRAME_TOP + FRAME_SIZE - 2);
  55. offs += CELL_INNER_SIZE + 1;
  56. }
  57. offs = FRAME_TOP + CELL_INNER_SIZE + 1;
  58. for(uint8_t i = 0; i < CELLS_COUNT - 1; i++) {
  59. canvas_draw_line(canvas, FRAME_LEFT + 1, offs, FRAME_LEFT + FRAME_SIZE - 2, offs);
  60. offs += CELL_INNER_SIZE + 1;
  61. }
  62. }
  63. static void draw_digit(Canvas* canvas, uint8_t row, uint8_t column, uint8_t value) {
  64. if(value == 0) return;
  65. uint8_t left = FRAME_LEFT + 1 + (column * (CELL_INNER_SIZE + 1));
  66. uint8_t top = FRAME_TOP + 1 + (row * (CELL_INNER_SIZE + 1));
  67. for(uint8_t r = 0; r < CELL_INNER_SIZE; r++) {
  68. for(uint8_t c = 0; c < CELL_INNER_SIZE; c++) {
  69. if(digits[value - 1][r][c] == 1) {
  70. canvas_draw_dot(canvas, left + c, top + r);
  71. }
  72. }
  73. }
  74. }
  75. static void draw_table(Canvas* canvas, const uint8_t table[CELLS_COUNT][CELLS_COUNT]) {
  76. for(uint8_t row = 0; row < CELLS_COUNT; row++) {
  77. for(uint8_t column = 0; column < CELLS_COUNT; column++) {
  78. draw_digit(canvas, row, column, table[row][column]);
  79. }
  80. }
  81. }
  82. static void gray_canvas(Canvas* const canvas) {
  83. canvas_set_color(canvas, ColorWhite);
  84. for(int x = 0; x < 128; x += 2) {
  85. for(int y = 0; y < 64; y++) {
  86. canvas_draw_dot(canvas, x + (y % 2 == 1 ? 0 : 1), y);
  87. }
  88. }
  89. }
  90. static void draw_callback(Canvas* const canvas, void* ctx) {
  91. furi_assert(ctx);
  92. const GameState* game_state = ctx;
  93. furi_mutex_acquire(game_state->mutex, FuriWaitForever);
  94. canvas_clear(canvas);
  95. draw_frame(canvas);
  96. draw_table(canvas, game_state->table);
  97. canvas_set_font(canvas, FontPrimary);
  98. canvas_draw_str_aligned(canvas, 128, FRAME_TOP, AlignRight, AlignTop, "Score");
  99. canvas_draw_str_aligned(canvas, 128, FRAME_TOP + 20, AlignRight, AlignTop, "Moves");
  100. canvas_draw_str_aligned(canvas, 128, FRAME_TOP + 40, AlignRight, AlignTop, "Top Score");
  101. int bufSize = 12;
  102. char buf[bufSize];
  103. snprintf(buf, sizeof(buf), "%lu", game_state->score);
  104. canvas_set_font(canvas, FontSecondary);
  105. canvas_draw_str_aligned(canvas, 128, FRAME_TOP + 10, AlignRight, AlignTop, buf);
  106. memset(buf, 0, bufSize);
  107. snprintf(buf, sizeof(buf), "%lu", game_state->moves);
  108. canvas_set_font(canvas, FontSecondary);
  109. canvas_draw_str_aligned(canvas, 128, FRAME_TOP + 30, AlignRight, AlignTop, buf);
  110. memset(buf, 0, bufSize);
  111. snprintf(buf, sizeof(buf), "%lu", game_state->top_score);
  112. canvas_set_font(canvas, FontSecondary);
  113. canvas_draw_str_aligned(canvas, 128, FRAME_TOP + 50, AlignRight, AlignTop, buf);
  114. if(game_state->state == GameStateMenu) {
  115. gray_canvas(canvas);
  116. canvas_set_color(canvas, ColorWhite);
  117. canvas_draw_rbox(canvas, 28, 16, 72, 32, 4);
  118. canvas_set_color(canvas, ColorBlack);
  119. canvas_draw_rframe(canvas, 28, 16, 72, 32, 4);
  120. for(int i = 0; i < MENU_ITEMS_COUNT; i++) {
  121. if(i == game_state->selected_menu_item) {
  122. canvas_set_color(canvas, ColorBlack);
  123. canvas_draw_box(canvas, 34, 20 + 12 * i, 60, 12);
  124. }
  125. canvas_set_color(
  126. canvas, i == game_state->selected_menu_item ? ColorWhite : ColorBlack);
  127. canvas_draw_str_aligned(
  128. canvas, 64, 26 + 12 * i, AlignCenter, AlignCenter, popup_menu_strings[i]);
  129. }
  130. } else if(game_state->state == GameStateGameOver) {
  131. gray_canvas(canvas);
  132. bool record_broken = game_state->score > game_state->top_score;
  133. canvas_set_color(canvas, ColorWhite);
  134. canvas_draw_rbox(canvas, 14, 12, 100, 40, 4);
  135. canvas_set_color(canvas, ColorBlack);
  136. canvas_draw_line(canvas, 14, 26, 114, 26);
  137. canvas_draw_rframe(canvas, 14, 12, 100, 40, 4);
  138. canvas_set_font(canvas, FontPrimary);
  139. canvas_draw_str_aligned(canvas, 64, 15, AlignCenter, AlignTop, "Game Over");
  140. canvas_set_font(canvas, FontSecondary);
  141. if(record_broken) {
  142. canvas_draw_str_aligned(canvas, 64, 29, AlignCenter, AlignTop, "New Top Score!!!");
  143. } else {
  144. canvas_draw_str_aligned(canvas, 64, 29, AlignCenter, AlignTop, "Your Score");
  145. }
  146. memset(buf, 0, bufSize);
  147. snprintf(buf, sizeof(buf), "%lu", game_state->score);
  148. canvas_set_font(canvas, FontPrimary);
  149. canvas_draw_str_aligned(canvas, 64, 48, AlignCenter, AlignBottom, buf);
  150. }
  151. furi_mutex_release(game_state->mutex);
  152. }
  153. void calculate_move_to_left(uint8_t arr[], MoveResult* const move_result) {
  154. uint8_t index = 0;
  155. uint8_t next_index;
  156. uint8_t offset;
  157. bool was_moved;
  158. while(index < CELLS_COUNT - 1) {
  159. // find offset from [index] to next non-empty value
  160. offset = 1;
  161. while(index + offset < CELLS_COUNT && arr[index + offset] == 0)
  162. offset++;
  163. // if all remaining values in this row are empty then go to next row
  164. if(index + offset >= CELLS_COUNT) break;
  165. // if current cell is empty then shift all cells [index+offset .. CELLS_COUNT-1] to [index]
  166. if(arr[index] == 0) {
  167. was_moved = shift_array_to_left(CELLS_COUNT, arr, index, offset);
  168. if(was_moved) move_result->is_table_updated = true;
  169. }
  170. next_index = index + 1;
  171. if(arr[next_index] == 0) {
  172. // find offset from [next_index] to next non-empty value
  173. offset = 1;
  174. while(next_index + offset < CELLS_COUNT && arr[next_index + offset] == 0)
  175. offset++;
  176. // if all remaining values in this row are empty then go to next row
  177. if(next_index + offset >= CELLS_COUNT) break;
  178. // if next cell is empty then shift cells [next_index+offset .. CELLS_COUNT-1] to [next_index]
  179. was_moved = shift_array_to_left(CELLS_COUNT, arr, next_index, offset);
  180. if(was_moved) move_result->is_table_updated = true;
  181. }
  182. if(arr[index] == arr[next_index]) {
  183. arr[index]++;
  184. shift_array_to_left(CELLS_COUNT, arr, next_index, 1);
  185. move_result->is_table_updated = true;
  186. move_result->points += 2 << (arr[index] - 1);
  187. }
  188. index++;
  189. }
  190. }
  191. void move_left(uint8_t table[CELLS_COUNT][CELLS_COUNT], MoveResult* const move_result) {
  192. for(uint8_t row_index = 0; row_index < CELLS_COUNT; row_index++) {
  193. calculate_move_to_left(table[row_index], move_result);
  194. }
  195. }
  196. void move_right(uint8_t table[CELLS_COUNT][CELLS_COUNT], MoveResult* const move_result) {
  197. for(uint8_t row_index = 0; row_index < CELLS_COUNT; row_index++) {
  198. reverse_array(CELLS_COUNT, table[row_index]);
  199. calculate_move_to_left(table[row_index], move_result);
  200. reverse_array(CELLS_COUNT, table[row_index]);
  201. }
  202. }
  203. void move_up(uint8_t table[CELLS_COUNT][CELLS_COUNT], MoveResult* const move_result) {
  204. uint8_t column[CELLS_COUNT];
  205. for(uint8_t column_index = 0; column_index < CELLS_COUNT; column_index++) {
  206. get_column_from_array(CELLS_COUNT, CELLS_COUNT, table, column_index, column);
  207. calculate_move_to_left(column, move_result);
  208. set_column_to_array(CELLS_COUNT, CELLS_COUNT, table, column_index, column);
  209. }
  210. }
  211. void move_down(uint8_t table[CELLS_COUNT][CELLS_COUNT], MoveResult* const move_result) {
  212. uint8_t column[CELLS_COUNT];
  213. for(uint8_t column_index = 0; column_index < CELLS_COUNT; column_index++) {
  214. get_column_from_array(CELLS_COUNT, CELLS_COUNT, table, column_index, column);
  215. reverse_array(CELLS_COUNT, column);
  216. calculate_move_to_left(column, move_result);
  217. reverse_array(CELLS_COUNT, column);
  218. set_column_to_array(CELLS_COUNT, CELLS_COUNT, table, column_index, column);
  219. }
  220. }
  221. void add_new_digit(GameState* const game_state) {
  222. uint8_t empty_cell_indexes[CELLS_COUNT * CELLS_COUNT];
  223. uint8_t empty_cells_count = 0;
  224. for(uint8_t i = 0; i < CELLS_COUNT; i++) {
  225. for(uint8_t j = 0; j < CELLS_COUNT; j++) {
  226. if(game_state->table[i][j] == 0) {
  227. empty_cell_indexes[empty_cells_count++] = i * CELLS_COUNT + j;
  228. }
  229. }
  230. }
  231. if(empty_cells_count == 0) return;
  232. int random_empty_cell_index = empty_cell_indexes[random() % empty_cells_count];
  233. uint8_t row = random_empty_cell_index / CELLS_COUNT;
  234. uint8_t col = random_empty_cell_index % CELLS_COUNT;
  235. int random_value_percent = random() % 100;
  236. game_state->table[row][col] = random_value_percent < 90 ? 1 : 2; // 90% for 2, 25% for 4
  237. }
  238. void init_game(GameState* const game_state, bool clear_top_score) {
  239. memset(game_state->table, 0, CELLS_COUNT * CELLS_COUNT * sizeof(uint8_t));
  240. add_new_digit(game_state);
  241. add_new_digit(game_state);
  242. game_state->score = 0;
  243. game_state->moves = 0;
  244. game_state->state = GameStateInProgress;
  245. game_state->selected_menu_item = 0;
  246. if(clear_top_score) {
  247. game_state->top_score = 0;
  248. }
  249. }
  250. bool load_game(GameState* game_state) {
  251. Storage* storage = furi_record_open(RECORD_STORAGE);
  252. storage_common_migrate(storage, EXT_PATH("apps/Games/game_2048.save"), SAVING_FILENAME);
  253. File* file = storage_file_alloc(storage);
  254. uint16_t bytes_readed = 0;
  255. if(storage_file_open(file, SAVING_FILENAME, FSAM_READ, FSOM_OPEN_EXISTING)) {
  256. bytes_readed = storage_file_read(file, game_state, sizeof(GameState));
  257. }
  258. storage_file_close(file);
  259. storage_file_free(file);
  260. furi_record_close(RECORD_STORAGE);
  261. return bytes_readed == sizeof(GameState);
  262. }
  263. void save_game(GameState* game_state) {
  264. Storage* storage = furi_record_open(RECORD_STORAGE);
  265. File* file = storage_file_alloc(storage);
  266. if(storage_file_open(file, SAVING_FILENAME, FSAM_WRITE, FSOM_CREATE_ALWAYS)) {
  267. storage_file_write(file, game_state, sizeof(GameState));
  268. }
  269. storage_file_close(file);
  270. storage_file_free(file);
  271. furi_record_close(RECORD_STORAGE);
  272. }
  273. bool is_game_over(GameState* const game_state) {
  274. FURI_LOG_I("is_game_over", "====check====");
  275. // check if table contains at least one empty cell
  276. for(uint8_t i = 0; i < CELLS_COUNT; i++) {
  277. for(uint8_t j = 0; j < CELLS_COUNT; j++) {
  278. if(game_state->table[i][j] == 0) {
  279. FURI_LOG_I("is_game_over", "has empty cells");
  280. return false;
  281. }
  282. }
  283. }
  284. FURI_LOG_I("is_game_over", "no empty cells");
  285. uint8_t tmp_table[CELLS_COUNT][CELLS_COUNT];
  286. MoveResult* tmp_move_result = malloc(sizeof(MoveResult));
  287. // check if we can move to any direction
  288. memcpy(tmp_table, game_state->table, CELLS_COUNT * CELLS_COUNT * sizeof(uint8_t));
  289. move_left(tmp_table, tmp_move_result);
  290. if(tmp_move_result->is_table_updated) return false;
  291. FURI_LOG_I("is_game_over", "can't move left");
  292. memcpy(tmp_table, game_state->table, CELLS_COUNT * CELLS_COUNT * sizeof(uint8_t));
  293. move_right(tmp_table, tmp_move_result);
  294. if(tmp_move_result->is_table_updated) return false;
  295. FURI_LOG_I("is_game_over", "can't move right");
  296. memcpy(tmp_table, game_state->table, CELLS_COUNT * CELLS_COUNT * sizeof(uint8_t));
  297. move_up(tmp_table, tmp_move_result);
  298. if(tmp_move_result->is_table_updated) return false;
  299. FURI_LOG_I("is_game_over", "can't move up");
  300. memcpy(tmp_table, game_state->table, CELLS_COUNT * CELLS_COUNT * sizeof(uint8_t));
  301. move_down(tmp_table, tmp_move_result);
  302. if(tmp_move_result->is_table_updated) return false;
  303. FURI_LOG_I("is_game_over", "can't move down");
  304. return true;
  305. }
  306. int32_t game_2048_app() {
  307. GameState* game_state = malloc(sizeof(GameState));
  308. if(!load_game(game_state)) {
  309. init_game(game_state, true);
  310. }
  311. MoveResult* move_result = malloc(sizeof(MoveResult));
  312. game_state->mutex = furi_mutex_alloc(FuriMutexTypeNormal);
  313. if(!game_state->mutex) {
  314. FURI_LOG_E("2048Game", "cannot create mutex\r\n");
  315. free(game_state);
  316. return 255;
  317. }
  318. InputEvent input;
  319. FuriMessageQueue* event_queue = furi_message_queue_alloc(8, sizeof(InputEvent));
  320. ViewPort* view_port = view_port_alloc();
  321. view_port_draw_callback_set(view_port, draw_callback, game_state);
  322. view_port_input_callback_set(view_port, input_callback, event_queue);
  323. Gui* gui = furi_record_open(RECORD_GUI);
  324. gui_add_view_port(gui, view_port, GuiLayerFullscreen);
  325. // Call dolphin deed on game start
  326. dolphin_deed(DolphinDeedPluginGameStart);
  327. bool is_finished = false;
  328. while(!is_finished) {
  329. FuriStatus event_status = furi_message_queue_get(event_queue, &input, FuriWaitForever);
  330. if(event_status == FuriStatusOk) {
  331. // handle only press event, ignore repeat/release events
  332. if(input.type != InputTypePress) continue;
  333. furi_mutex_acquire(game_state->mutex, FuriWaitForever);
  334. switch(game_state->state) {
  335. case GameStateMenu:
  336. switch(input.key) {
  337. case InputKeyUp:
  338. game_state->selected_menu_item--;
  339. if(game_state->selected_menu_item < 0) {
  340. game_state->selected_menu_item = MENU_ITEMS_COUNT - 1;
  341. }
  342. break;
  343. case InputKeyDown:
  344. game_state->selected_menu_item++;
  345. if(game_state->selected_menu_item >= MENU_ITEMS_COUNT) {
  346. game_state->selected_menu_item = 0;
  347. }
  348. break;
  349. case InputKeyOk:
  350. if(game_state->selected_menu_item == 1) {
  351. // new game
  352. init_game(game_state, false);
  353. save_game(game_state);
  354. }
  355. game_state->state = GameStateInProgress;
  356. break;
  357. case InputKeyBack:
  358. game_state->state = GameStateInProgress;
  359. break;
  360. default:
  361. break;
  362. }
  363. break;
  364. case GameStateInProgress:
  365. move_result->is_table_updated = false;
  366. move_result->points = 0;
  367. switch(input.key) {
  368. case InputKeyLeft:
  369. move_left(game_state->table, move_result);
  370. break;
  371. case InputKeyRight:
  372. move_right(game_state->table, move_result);
  373. break;
  374. case InputKeyUp:
  375. move_up(game_state->table, move_result);
  376. break;
  377. case InputKeyDown:
  378. move_down(game_state->table, move_result);
  379. break;
  380. case InputKeyOk:
  381. game_state->state = GameStateMenu;
  382. game_state->selected_menu_item = 0;
  383. break;
  384. case InputKeyBack:
  385. save_game(game_state);
  386. is_finished = true;
  387. break;
  388. case InputKeyMAX:
  389. break;
  390. }
  391. game_state->score += move_result->points;
  392. if(move_result->is_table_updated) {
  393. game_state->moves++;
  394. add_new_digit(game_state);
  395. }
  396. if(is_game_over(game_state)) {
  397. game_state->state = GameStateGameOver;
  398. if(game_state->score >= game_state->top_score) {
  399. game_state->top_score = game_state->score;
  400. }
  401. }
  402. break;
  403. case GameStateGameOver:
  404. if(input.key == InputKeyOk || input.key == InputKeyBack) {
  405. init_game(game_state, false);
  406. save_game(game_state);
  407. }
  408. }
  409. furi_mutex_release(game_state->mutex);
  410. view_port_update(view_port);
  411. }
  412. }
  413. gui_remove_view_port(gui, view_port);
  414. furi_record_close(RECORD_GUI);
  415. view_port_free(view_port);
  416. furi_message_queue_free(event_queue);
  417. furi_mutex_free(game_state->mutex);
  418. free(game_state);
  419. free(move_result);
  420. return 0;
  421. }