|
| 1 | +#include "board.h" |
| 2 | + |
| 3 | +bool board_new(struct Board **board, SDL_Renderer *renderer) { |
| 4 | + *board = calloc(1, sizeof(struct Board)); |
| 5 | + if (*board == NULL) { |
| 6 | + fprintf(stderr, "Error in calloc of new Board.\n"); |
| 7 | + return false; |
| 8 | + } |
| 9 | + struct Board *b = *board; |
| 10 | + |
| 11 | + b->renderer = renderer; |
| 12 | + b->rows = WINDOW_HEIGHT / SIZE; |
| 13 | + b->columns = WINDOW_WIDTH / SIZE; |
| 14 | + b->rect.w = SIZE - 1; |
| 15 | + b->rect.h = SIZE - 1; |
| 16 | + |
| 17 | + b->board = calloc(1, sizeof(bool) * (Uint64)(b->rows * b->columns)); |
| 18 | + if (b->board == NULL) { |
| 19 | + fprintf(stderr, "Error in calloc of new board.\n"); |
| 20 | + return false; |
| 21 | + } |
| 22 | + |
| 23 | + b->next_board = calloc(1, sizeof(bool) * (Uint64)(b->rows * b->columns)); |
| 24 | + if (b->next_board == NULL) { |
| 25 | + fprintf(stderr, "Error in calloc of new board.\n"); |
| 26 | + return false; |
| 27 | + } |
| 28 | + |
| 29 | + board_reset(b); |
| 30 | + |
| 31 | + return true; |
| 32 | +} |
| 33 | + |
| 34 | +void board_free(struct Board **board) { |
| 35 | + if (*board) { |
| 36 | + free((*board)->board); |
| 37 | + (*board)->board = NULL; |
| 38 | + |
| 39 | + free((*board)->next_board); |
| 40 | + (*board)->next_board = NULL; |
| 41 | + |
| 42 | + (*board)->renderer = NULL; |
| 43 | + |
| 44 | + free(*board); |
| 45 | + *board = NULL; |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +void board_reset(struct Board *b) { |
| 50 | + for (int row = 0; row < b->rows * b->columns; row += b->columns) { |
| 51 | + for (int column = 0; column < b->columns; column++) { |
| 52 | + if (rand() % 2 == 0) { |
| 53 | + b->board[row + column] = true; |
| 54 | + } else { |
| 55 | + b->board[row + column] = false; |
| 56 | + } |
| 57 | + } |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +void board_clear(struct Board *b) { |
| 62 | + for (int row = 0; row < b->rows * b->columns; row += b->columns) { |
| 63 | + for (int column = 0; column < b->columns; column++) { |
| 64 | + b->board[row + column] = false; |
| 65 | + } |
| 66 | + } |
| 67 | +} |
| 68 | + |
| 69 | +void board_draw(struct Board *b) { |
| 70 | + SDL_SetRenderDrawColor(b->renderer, CELL_COLOR); |
| 71 | + for (int row = 0; row < b->rows; row++) { |
| 72 | + b->rect.y = SIZE * row; |
| 73 | + for (int column = 0; column < b->columns; column++) { |
| 74 | + b->rect.x = SIZE * column; |
| 75 | + if (b->board[row * b->columns + column]) { |
| 76 | + SDL_RenderFillRect(b->renderer, &b->rect); |
| 77 | + } |
| 78 | + } |
| 79 | + } |
| 80 | +} |
0 commit comments