So_long/srcs/utils_2.c

94 lines
2.7 KiB
C

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* utils_2.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lfirmin <lfirmin@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/11/13 12:34:24 by lfirmin #+# #+# */
/* Updated: 2024/11/13 12:34:24 by lfirmin ### ########.fr */
/* */
/* ************************************************************************** */
#include "../include/so_long.h"
int close_game(t_game *game)
{
if (!game)
return (0);
if (game->img_floor)
mlx_destroy_image(game->mlx, game->img_floor);
if (game->img_wall)
mlx_destroy_image(game->mlx, game->img_wall);
if (game->img_player)
mlx_destroy_image(game->mlx, game->img_player);
if (game->img_collect)
mlx_destroy_image(game->mlx, game->img_collect);
if (game->img_exit)
mlx_destroy_image(game->mlx, game->img_exit);
if (game->win)
mlx_destroy_window(game->mlx, game->win);
if (game->mlx)
{
mlx_destroy_display(game->mlx);
free(game->mlx);
}
clean_data(game->data);
free(game);
return (exit(0), 0);
}
void update_player_position(t_game *game, int x, int y)
{
int old_x;
int old_y;
old_x = game->player_x;
old_y = game->player_y;
game->map[old_y][old_x] = '0';
if (old_x == game->exit_x && old_y == game->exit_y)
game->map[old_y][old_x] = 'E';
draw_tile(game, game->map[old_y][old_x], old_x, old_y);
game->map[y][x] = 'P';
draw_tile(game, 'P', x, y);
game->player_x = x;
game->player_y = y;
game->moves++;
printf("Moves: %d\n", game->moves);
}
void move_player(t_game *game, int new_x, int new_y)
{
char current_pos;
current_pos = game->map[new_y][new_x];
if (current_pos == 'E' && game->collectibles == 0)
{
ft_printf_fd(1, "Congratulations! You won in %d moves!\n", \
game->moves + 1);
close_game(game);
}
if (current_pos == 'C')
{
game->collectibles--;
if (game->collectibles == 0)
draw_tile(game, 'E', game->exit_x, game->exit_y);
}
update_player_position(game, new_x, new_y);
}
int is_valid_move(t_game *game, int x, int y)
{
if (x < 0 || x >= game->map_width || y < 0 || y >= game->map_height)
return (0);
if (game->map[y][x] == '1')
return (0);
if (game->map[y][x] == 'E')
{
if (game->collectibles == 0)
return (1);
return (1);
}
return (1);
}