game_2048.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  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 "/ext/apps/Games"
  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(u_int8_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) offset++;
  162. // if all remaining values in this row are empty then go to next row
  163. if(index + offset >= CELLS_COUNT) break;
  164. // if current cell is empty then shift all cells [index+offset .. CELLS_COUNT-1] to [index]
  165. if(arr[index] == 0) {
  166. was_moved = shift_array_to_left(CELLS_COUNT, arr, index, offset);
  167. if(was_moved) move_result->is_table_updated = true;
  168. }
  169. next_index = index + 1;
  170. if(arr[next_index] == 0) {
  171. // find offset from [next_index] to next non-empty value
  172. offset = 1;
  173. while(next_index + offset < CELLS_COUNT && arr[next_index + offset] == 0) offset++;
  174. // if all remaining values in this row are empty then go to next row
  175. if(next_index + offset >= CELLS_COUNT) break;
  176. // if next cell is empty then shift cells [next_index+offset .. CELLS_COUNT-1] to [next_index]
  177. was_moved = shift_array_to_left(CELLS_COUNT, arr, next_index, offset);
  178. if(was_moved) move_result->is_table_updated = true;
  179. }
  180. if(arr[index] == arr[next_index]) {
  181. arr[index]++;
  182. shift_array_to_left(CELLS_COUNT, arr, next_index, 1);
  183. move_result->is_table_updated = true;
  184. move_result->points += 2 << (arr[index] - 1);
  185. }
  186. index++;
  187. }
  188. }
  189. void move_left(uint8_t table[CELLS_COUNT][CELLS_COUNT], MoveResult* const move_result) {
  190. for(uint8_t row_index = 0; row_index < CELLS_COUNT; row_index++) {
  191. calculate_move_to_left(table[row_index], move_result);
  192. }
  193. }
  194. void move_right(uint8_t table[CELLS_COUNT][CELLS_COUNT], MoveResult* const move_result) {
  195. for(uint8_t row_index = 0; row_index < CELLS_COUNT; row_index++) {
  196. reverse_array(CELLS_COUNT, table[row_index]);
  197. calculate_move_to_left(table[row_index], move_result);
  198. reverse_array(CELLS_COUNT, table[row_index]);
  199. }
  200. }
  201. void move_up(uint8_t table[CELLS_COUNT][CELLS_COUNT], MoveResult* const move_result) {
  202. uint8_t column[CELLS_COUNT];
  203. for(uint8_t column_index = 0; column_index < CELLS_COUNT; column_index++) {
  204. get_column_from_array(CELLS_COUNT, CELLS_COUNT, table, column_index, column);
  205. calculate_move_to_left(column, move_result);
  206. set_column_to_array(CELLS_COUNT, CELLS_COUNT, table, column_index, column);
  207. }
  208. }
  209. void move_down(uint8_t table[CELLS_COUNT][CELLS_COUNT], MoveResult* const move_result) {
  210. uint8_t column[CELLS_COUNT];
  211. for(uint8_t column_index = 0; column_index < CELLS_COUNT; column_index++) {
  212. get_column_from_array(CELLS_COUNT, CELLS_COUNT, table, column_index, column);
  213. reverse_array(CELLS_COUNT, column);
  214. calculate_move_to_left(column, move_result);
  215. reverse_array(CELLS_COUNT, column);
  216. set_column_to_array(CELLS_COUNT, CELLS_COUNT, table, column_index, column);
  217. }
  218. }
  219. void add_new_digit(GameState* const game_state) {
  220. uint8_t empty_cell_indexes[CELLS_COUNT * CELLS_COUNT];
  221. uint8_t empty_cells_count = 0;
  222. for(u_int8_t i = 0; i < CELLS_COUNT; i++) {
  223. for(u_int8_t j = 0; j < CELLS_COUNT; j++) {
  224. if(game_state->table[i][j] == 0) {
  225. empty_cell_indexes[empty_cells_count++] = i * CELLS_COUNT + j;
  226. }
  227. }
  228. }
  229. if(empty_cells_count == 0) return;
  230. int random_empty_cell_index = empty_cell_indexes[random() % empty_cells_count];
  231. u_int8_t row = random_empty_cell_index / CELLS_COUNT;
  232. u_int8_t col = random_empty_cell_index % CELLS_COUNT;
  233. int random_value_percent = random() % 100;
  234. game_state->table[row][col] = random_value_percent < 90 ? 1 : 2; // 90% for 2, 25% for 4
  235. }
  236. void init_game(GameState* const game_state, bool clear_top_score) {
  237. memset(game_state->table, 0, CELLS_COUNT * CELLS_COUNT * sizeof(uint8_t));
  238. add_new_digit(game_state);
  239. add_new_digit(game_state);
  240. game_state->score = 0;
  241. game_state->moves = 0;
  242. game_state->state = GameStateInProgress;
  243. game_state->selected_menu_item = 0;
  244. if(clear_top_score) {
  245. game_state->top_score = 0;
  246. }
  247. }
  248. bool load_game(GameState* game_state) {
  249. Storage* storage = furi_record_open(RECORD_STORAGE);
  250. File* file = storage_file_alloc(storage);
  251. uint16_t bytes_readed = 0;
  252. if(storage_file_open(file, SAVING_FILENAME, FSAM_READ, FSOM_OPEN_EXISTING)) {
  253. bytes_readed = storage_file_read(file, game_state, sizeof(GameState));
  254. }
  255. storage_file_close(file);
  256. storage_file_free(file);
  257. furi_record_close(RECORD_STORAGE);
  258. return bytes_readed == sizeof(GameState);
  259. }
  260. void save_game(GameState* game_state) {
  261. Storage* storage = furi_record_open(RECORD_STORAGE);
  262. if(storage_common_stat(storage, SAVING_DIRECTORY, NULL) == FSE_NOT_EXIST) {
  263. if(!storage_simply_mkdir(storage, SAVING_DIRECTORY)) {
  264. return;
  265. }
  266. }
  267. File* file = storage_file_alloc(storage);
  268. if(storage_file_open(file, SAVING_FILENAME, FSAM_WRITE, FSOM_CREATE_ALWAYS)) {
  269. storage_file_write(file, game_state, sizeof(GameState));
  270. }
  271. storage_file_close(file);
  272. storage_file_free(file);
  273. furi_record_close(RECORD_STORAGE);
  274. }
  275. bool is_game_over(GameState* const game_state) {
  276. FURI_LOG_I("is_game_over", "====check====");
  277. // check if table contains at least one empty cell
  278. for(uint8_t i = 0; i < CELLS_COUNT; i++) {
  279. for(u_int8_t j = 0; j < CELLS_COUNT; j++) {
  280. if(game_state->table[i][j] == 0) {
  281. FURI_LOG_I("is_game_over", "has empty cells");
  282. return false;
  283. }
  284. }
  285. }
  286. FURI_LOG_I("is_game_over", "no empty cells");
  287. uint8_t tmp_table[CELLS_COUNT][CELLS_COUNT];
  288. MoveResult* tmp_move_result = malloc(sizeof(MoveResult));
  289. // check if we can move to any direction
  290. memcpy(tmp_table, game_state->table, CELLS_COUNT * CELLS_COUNT * sizeof(uint8_t));
  291. move_left(tmp_table, tmp_move_result);
  292. if(tmp_move_result->is_table_updated) return false;
  293. FURI_LOG_I("is_game_over", "can't move left");
  294. memcpy(tmp_table, game_state->table, CELLS_COUNT * CELLS_COUNT * sizeof(uint8_t));
  295. move_right(tmp_table, tmp_move_result);
  296. if(tmp_move_result->is_table_updated) return false;
  297. FURI_LOG_I("is_game_over", "can't move right");
  298. memcpy(tmp_table, game_state->table, CELLS_COUNT * CELLS_COUNT * sizeof(uint8_t));
  299. move_up(tmp_table, tmp_move_result);
  300. if(tmp_move_result->is_table_updated) return false;
  301. FURI_LOG_I("is_game_over", "can't move up");
  302. memcpy(tmp_table, game_state->table, CELLS_COUNT * CELLS_COUNT * sizeof(uint8_t));
  303. move_down(tmp_table, tmp_move_result);
  304. if(tmp_move_result->is_table_updated) return false;
  305. FURI_LOG_I("is_game_over", "can't move down");
  306. return true;
  307. }
  308. int32_t game_2048_app() {
  309. GameState* game_state = malloc(sizeof(GameState));
  310. if(!load_game(game_state)) {
  311. init_game(game_state, true);
  312. }
  313. MoveResult* move_result = malloc(sizeof(MoveResult));
  314. game_state->mutex = furi_mutex_alloc(FuriMutexTypeNormal);
  315. if(!game_state->mutex) {
  316. FURI_LOG_E("2048Game", "cannot create mutex\r\n");
  317. free(game_state);
  318. return 255;
  319. }
  320. InputEvent input;
  321. FuriMessageQueue* event_queue = furi_message_queue_alloc(8, sizeof(InputEvent));
  322. ViewPort* view_port = view_port_alloc();
  323. view_port_draw_callback_set(view_port, draw_callback, game_state);
  324. view_port_input_callback_set(view_port, input_callback, event_queue);
  325. Gui* gui = furi_record_open(RECORD_GUI);
  326. gui_add_view_port(gui, view_port, GuiLayerFullscreen);
  327. // Call dolphin deed on game start
  328. dolphin_deed(DolphinDeedPluginGameStart);
  329. bool is_finished = false;
  330. while(!is_finished) {
  331. FuriStatus event_status = furi_message_queue_get(event_queue, &input, FuriWaitForever);
  332. if(event_status == FuriStatusOk) {
  333. // handle only press event, ignore repeat/release events
  334. if(input.type != InputTypePress) continue;
  335. furi_mutex_acquire(game_state->mutex, FuriWaitForever);
  336. switch(game_state->state) {
  337. case GameStateMenu:
  338. switch(input.key) {
  339. case InputKeyUp:
  340. game_state->selected_menu_item--;
  341. if(game_state->selected_menu_item < 0) {
  342. game_state->selected_menu_item = MENU_ITEMS_COUNT - 1;
  343. }
  344. break;
  345. case InputKeyDown:
  346. game_state->selected_menu_item++;
  347. if(game_state->selected_menu_item >= MENU_ITEMS_COUNT) {
  348. game_state->selected_menu_item = 0;
  349. }
  350. break;
  351. case InputKeyOk:
  352. if(game_state->selected_menu_item == 1) {
  353. // new game
  354. init_game(game_state, false);
  355. save_game(game_state);
  356. }
  357. game_state->state = GameStateInProgress;
  358. break;
  359. case InputKeyBack:
  360. game_state->state = GameStateInProgress;
  361. break;
  362. default:
  363. break;
  364. }
  365. break;
  366. case GameStateInProgress:
  367. move_result->is_table_updated = false;
  368. move_result->points = 0;
  369. switch(input.key) {
  370. case InputKeyLeft:
  371. move_left(game_state->table, move_result);
  372. break;
  373. case InputKeyRight:
  374. move_right(game_state->table, move_result);
  375. break;
  376. case InputKeyUp:
  377. move_up(game_state->table, move_result);
  378. break;
  379. case InputKeyDown:
  380. move_down(game_state->table, move_result);
  381. break;
  382. case InputKeyOk:
  383. game_state->state = GameStateMenu;
  384. game_state->selected_menu_item = 0;
  385. break;
  386. case InputKeyBack:
  387. save_game(game_state);
  388. is_finished = true;
  389. break;
  390. case InputKeyMAX:
  391. break;
  392. }
  393. game_state->score += move_result->points;
  394. if(move_result->is_table_updated) {
  395. game_state->moves++;
  396. add_new_digit(game_state);
  397. }
  398. if(is_game_over(game_state)) {
  399. game_state->state = GameStateGameOver;
  400. if(game_state->score >= game_state->top_score) {
  401. game_state->top_score = game_state->score;
  402. }
  403. }
  404. break;
  405. case GameStateGameOver:
  406. if(input.key == InputKeyOk || input.key == InputKeyBack) {
  407. init_game(game_state, false);
  408. save_game(game_state);
  409. }
  410. }
  411. furi_mutex_release(game_state->mutex);
  412. view_port_update(view_port);
  413. }
  414. }
  415. gui_remove_view_port(gui, view_port);
  416. furi_record_close(RECORD_GUI);
  417. view_port_free(view_port);
  418. furi_message_queue_free(event_queue);
  419. furi_mutex_free(game_state->mutex);
  420. free(game_state);
  421. free(move_result);
  422. return 0;
  423. }