#include "map.h" #include "parsing_private.h" #include #include char **get_body(const char **file_content, size_t header_size) { char **body; size_t i; size_t len; len = 0; while (file_content[header_size + len] != NULL) len++; body = malloc((len + 1) * sizeof(char *)); if (body == NULL) return (NULL); body[len] = NULL; i = 0; while (i < len) { body[i] = ft_strdup(file_content[header_size + i]); if (body[i] == NULL) { ft_cancel((void **) body, i); return (NULL); } i++; } return (body); } int get_spawn_position(const char **body, long long *spawn_x, long long *spawn_y) { size_t x; size_t y; *spawn_x = -1; *spawn_y = -1; y = 0; while (body[y] != NULL) { x = 0; while (body[y][x] != '\0') { if (ft_is_in("NSEW", body[y][x])) { if (*spawn_x != -1) return (1); *spawn_x = x; *spawn_y = y; } x++; } y++; } if (*spawn_x == -1) return (2); return (0); } static int map_is_in_one_part(const char **body) { size_t y; y = ft_tablen((const void **) body) - 1; while (body[y][0] == '\0' || ft_contain_only(body[y], ' ')) y--; while (y > 0) { if (body[y][0] == '\0' || ft_contain_only(body[y], ' ')) return (1); y--; } return (0); } static int map_surround_check(char **body, size_t x, size_t y) { if (y == 0 || body[y] == NULL) return (1); if (x == 0 || body[y][x] == '\0') return (1); if (ft_is_in("21", body[y][x])) return (0); if (ft_is_in(" ", body[y][x])) return (1); body[y][x] = '2'; if (map_surround_check(body, x + 1, y)) return (1); if (map_surround_check(body, x - 1, y)) return (1); if (map_surround_check(body, x, y + 1)) return (1); if (map_surround_check(body, x, y - 1)) return (1); return (0); } static int map_surround(const char **body, t_map *map) { size_t i; char **copy; copy = malloc((ft_tablen((const void **) body) + 1) * sizeof(char *)); if (copy == NULL) return (1); i = 0; while (body[i] != NULL) { copy[i] = ft_strdup(body[i]); if (copy[i] == NULL) { ft_cancel((void **) copy, i); return (1); } i++; } copy[i] = NULL; if (map_surround_check(copy, map->spawn_x, map->spawn_y)) { ft_freer_tab_ultimate(1, copy); return (1); } ft_freer_tab_ultimate(1, copy); return (0); } int body_is_valid(const char **body, t_map *map) { int error; if (body == NULL) return (0); error = get_spawn_position(body, &map->spawn_x, &map->spawn_y); if (error == 1) { ft_eprintf("map: spawn position: multiple definition"); return (0); } else if (error == 2) { ft_eprintf("map: spawn position: not define"); return (0); } error = map_surround(body, map); if (error) { ft_eprintf("map: not surrounded"); return (0); } error = map_is_in_one_part(body); if (error) { ft_eprintf("map: splitted"); return (0); } return (1); }