summaryrefslogtreecommitdiff
path: root/map_pathfind.c
diff options
context:
space:
mode:
Diffstat (limited to 'map_pathfind.c')
-rw-r--r--map_pathfind.c86
1 files changed, 86 insertions, 0 deletions
diff --git a/map_pathfind.c b/map_pathfind.c
new file mode 100644
index 0000000..c1b0eb8
--- /dev/null
+++ b/map_pathfind.c
@@ -0,0 +1,86 @@
+/* ************************************************************************** */
+/* */
+/* ::: :::::::: */
+/* map_pathfind.c :+: :+: :+: */
+/* +:+ +:+ +:+ */
+/* By: kdx <kdx @student.42angouleme.fr +#+ +:+ +#+ */
+/* +#+#+#+#+#+ +#+ */
+/* Created: 2022/10/15 23:59:55 by kdx #+# #+# */
+/* Updated: 2022/10/16 00:45:47 by kdx ### ########.fr */
+/* */
+/* ************************************************************************** */
+
+#include "map.h"
+
+static t_err map_fill(t_map *map, int x, int y)
+{
+ unsigned char tile;
+ t_err rv;
+
+ if (x < 0 || y < 0 || (size_t)x >= map->width || (size_t)y >= map->height
+ || (map_get(map, x * TSIZE, y * TSIZE) & 128) != 0)
+ return (0);
+ tile = map_get(map, x * TSIZE, y * TSIZE);
+ map_set(map, x * TSIZE, y * TSIZE, tile | 128);
+ if (tile == TILE_WALL)
+ return (0);
+ if (tile == TILE_EXIT || tile == TILE_COLLECTIBLE)
+ rv = 1;
+ else
+ rv = 0;
+ return (rv + map_fill(map, x - 1, y) + map_fill(map, x + 1, y)
+ + map_fill(map, x, y - 1) + map_fill(map, x, y + 1));
+}
+
+static void find_player(t_map *map, int *x, int *y)
+{
+ *y = 0;
+ while ((size_t)(*y) < map->height)
+ {
+ *x = 0;
+ while ((size_t)(*x) < map->width)
+ {
+ if (map_get(map, *x * TSIZE, *y * TSIZE) == TILE_PLAYER)
+ return ;
+ *x += 1;
+ }
+ if (map_get(map, *x * TSIZE, *y * TSIZE) == TILE_PLAYER)
+ return ;
+ *y += 1;
+ }
+}
+
+static t_err expected_result(t_map *map)
+{
+ size_t i;
+ t_err expected;
+
+ i = 0;
+ expected = 0;
+ while (map->data[i] != '\0')
+ {
+ if (map->data[i] == TILE_EXIT
+ || map->data[i] == TILE_COLLECTIBLE)
+ expected += 1;
+ i += 1;
+ }
+ return (expected);
+}
+
+t_err map_pathfind(t_map *map)
+{
+ int x;
+ int y;
+ t_err rv;
+ size_t i;
+
+ find_player(map, &x, &y);
+ rv = map_fill(map, x, y);
+ i = 0;
+ while (map->data[i] != '\0')
+ {
+ map->data[i] &= 127;
+ i += 1;
+ }
+ return (rv == expected_result(map));
+}