game_2048.c 17 KB

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