#include "grid.h" #include #include void grid_init(grid_t *g, int cols, int rows) { if (!g) return; if (cols < 1) cols = 1; if (rows < 1) rows = 1; g->cols = cols; g->rows = rows; g->cells = calloc((size_t)cols * (size_t)rows, 1); g->show_lines = 1; } void grid_free(grid_t *g) { if (!g) return; free(g->cells); g->cells = NULL; g->cols = 0; g->rows = 0; } void grid_resize(grid_t *g, int new_cols, int new_rows) { if (!g) return; if (new_cols < 1) new_cols = 1; if (new_rows < 1) new_rows = 1; unsigned char *ncells = calloc((size_t)new_cols * (size_t)new_rows, 1); if (!ncells) return; int copy_cols = g->cols < new_cols ? g->cols : new_cols; int copy_rows = g->rows < new_rows ? g->rows : new_rows; for (int r = 0; r < copy_rows; r++) { memcpy(ncells + (size_t)r * new_cols, g->cells + (size_t)r * g->cols, (size_t)copy_cols); } free(g->cells); g->cells = ncells; g->cols = new_cols; g->rows = new_rows; } void grid_clear(grid_t *g) { if (!g || !g->cells) return; memset(g->cells, 0, (size_t)g->cols * (size_t)g->rows); } int grid_get(const grid_t *g, int c, int r) { if (!g || !g->cells) return 0; if (c < 0 || r < 0 || c >= g->cols || r >= g->rows) return 0; return g->cells[(size_t)r * g->cols + c]; } void grid_set(grid_t *g, int c, int r, int val) { if (!g || !g->cells) return; if (c < 0 || r < 0 || c >= g->cols || r >= g->rows) return; g->cells[(size_t)r * g->cols + c] = val ? 1 : 0; }