Small snake game in C
| 1 | #include "read_input.h" |
| 2 | |
| 3 | uint8_t read_input(keypress **input, size_t *input_len, bool *lock, bool is_broken, uint64_t delay) { |
| 4 | |
| 5 | size_t arr_len = ARR_LEN; |
| 6 | |
| 7 | if (!(*input = malloc(sizeof(keypress) * arr_len))) |
| 8 | return 0; |
| 9 | |
| 10 | struct pollfd polling[1]; |
| 11 | |
| 12 | polling[0].fd = STDIN_FILENO; |
| 13 | polling[0].events = POLLIN; |
| 14 | |
| 15 | if(is_broken) { |
| 16 | (*input)[0] = ESCAPE_KEY; |
| 17 | (*input_len)++; |
| 18 | |
| 19 | break_unfinished(); |
| 20 | } |
| 21 | |
| 22 | int is_poll = poll(polling, 1, delay); |
| 23 | |
| 24 | if (is_poll > 0 && polling[0].revents & POLLIN) { |
| 25 | |
| 26 | char string[256] = {}; |
| 27 | ssize_t length_string = read(STDIN_FILENO, string, sizeof(string) - 1); |
| 28 | |
| 29 | if (add_to_buf(string, length_string)) { |
| 30 | |
| 31 | do { |
| 32 | |
| 33 | if (*input_len >= arr_len) { |
| 34 | arr_len *= 2; |
| 35 | keypress *tmp = realloc(*input, sizeof(keypress) * arr_len); |
| 36 | if (tmp == NULL) { |
| 37 | free(*input); |
| 38 | return 0; |
| 39 | } |
| 40 | *input = tmp; |
| 41 | } |
| 42 | |
| 43 | (*input)[*input_len] = parse_input(); |
| 44 | |
| 45 | if ((*input)[*input_len] == INCOMPLETE) { |
| 46 | *lock = true; |
| 47 | break; |
| 48 | } |
| 49 | |
| 50 | } while ((*input)[(*input_len)++] != NO_KEY); |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | return 1; |
| 55 | } |
| 56 | |
| 57 | void free_input(keypress *input) { |
| 58 | free(input); |
| 59 | } |
| 60 | |
| 61 |