summaryrefslogtreecommitdiff
path: root/map_pathfind.c
blob: c1b0eb82da1e312d911b3da714723a25954ec5a5 (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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
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));
}