aboutsummaryrefslogtreecommitdiff
path: root/src/grid.c
blob: 35547795735ac16f5e2cd40e42b6b337fdda9e84 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include "grid.h"
#include "utils.h"
#include <stdio.h>
#include <stdlib.h>

Grid grid_create(unsigned int width, unsigned int height, char *fill)
{
	unsigned int mem_height = height * sizeof(char **);
	unsigned int mem_width = width * sizeof(char *);

	Dimensions dimens = {.width = width, .height = height};

	Grid grid = {.grid = malloc_s(mem_height), .dimens = dimens};

	// Fill the grid
	for (unsigned int y = 0; y < height; y++)
	{
		grid.grid[y] = malloc_s(mem_width);

		for (unsigned int x = 0; x < width; x++)
			grid.grid[y][x] = fill;
	}

	return grid;
}

char *grid_get(Grid grid, Position pos)
{
	return grid.grid[pos.y][pos.x];
}

void grid_set(Grid grid, Position pos, char *value)
{
	grid.grid[pos.y][pos.x] = value;
}

void grid_print(Grid grid)
{
	for (unsigned int y = 0; y < grid.dimens.height; y++)
	{
		for (unsigned int x = 0; x < grid.dimens.width; x++)
			printf("%s", grid.grid[y][x]);

		printf("\n");
	}
}

void grid_destroy(Grid grid)
{
	// Deallocate the memory of the grid
	for (unsigned int y = 0; y < grid.dimens.height; y++)
		free(grid.grid[y]);

	free(grid.grid);
}