diff options
Diffstat (limited to 'map.c')
| -rw-r--r-- | map.c | 47 |
1 files changed, 47 insertions, 0 deletions
@@ -5,6 +5,7 @@ #include "map.h" #include "config.h" #include "stack.h" +#include "error.h" Map empty_map(size_t width, size_t height) { Map map = malloc(sizeof(MapTile*) * height); @@ -93,6 +94,52 @@ Map rbt_maze_map(size_t width, size_t height, unsigned int seed) { return map; } +/* Reads the map from a file, saves size in `width` and `height` + * + * FILE FORMAT IS AS FOLLOWS: + * {WIDTH}x{HEIGHT} + * {EMPTY_CHAR}{WALL_CHAR}{START_CHAR}{END_CHAR} + * {MAP, one line at a time} + * + * EXAMPLE: + * 10x4 + * .#@x + * .......x.. + * ....###... + * ....#.#... + * ..@....... */ +/* TODO: handle errors better */ +Map file_plaintext_map(char *filename, size_t *width, size_t *height, Position *start_pos, Position *end_pos) { + FILE *file = fopen(filename, "r"); + if (file == NULL) { + error("Failed to open file %s\n", filename); + } + + if (fscanf(file, "%zux%zu\n", width, height) != 2) { + error("Failed reading size of file %s\n", filename); + } + + Map map = empty_map(*width, *height); + + char empty_char, wall_char, start_char, end_char; + if (fscanf(file, "%c%c%c%c\n", &empty_char, &wall_char, &start_char, &end_char) != 4) { + error("Failed reading chars of file %s\n", filename); + } + + for (size_t row = 0; row < *height; row++) { + for (size_t col = 0; col < *width; col++) { + char c = (char)fgetc(file); + if (c == empty_char) continue; + if (c == wall_char) { map[row][col] = WALL; continue; } + if (c == start_char) { start_pos->x = col; start_pos->y = row; continue; } + if (c == end_char) { end_pos->x = col; end_pos->y = row; continue; } + } + fgetc(file); + } + + return map; +} + /* FIXME: I don't think we need DRAW_MAP_OFFSET_{X,Y} anymore * Although, at the same time, it does make less magic values, so I guess it's fine */ /* TODO: Maybe add an option to render with ▄? that doubles the resolution, but requires us to use ncursesw, probably. */ |
