cub3d/src/game.c
2025-05-23 17:30:04 +02:00

167 lines
3.5 KiB
C

/* ************************************************************************** */
/* */
/* :::::::: */
/* game.c :+: :+: */
/* +:+ */
/* By: qmennen <qmennen@student.codam.nl> +#+ */
/* +#+ */
/* Created: 2025/04/15 15:46:08 by qmennen #+# #+# */
/* Updated: 2025/05/23 17:20:34 by whaffman ######## odam.nl */
/* */
/* ************************************************************************** */
#include "cub3d.h"
#include "glad.h"
#include "MLX42_Int.h"
int game_create(t_game **game)
{
*game = malloc(sizeof(t_game));
if (!game)
return (FAILURE);
memset(*game, 0, sizeof(t_game));
(*game)->fps = 20;
return (SUCCESS);
}
void free_game(t_game **game)
{
if (game && *game)
{
if ((*game)->screen)
free((*game)->screen);
if ((*game)->player)
free((*game)->player);
if ((*game)->map)
free((*game)->map);
free(*game);
}
}
int battery_color(float battery)
{
if (battery > 0.5f)
return (0x00FF0066);
else if (battery > 0.25f)
return (0xFFFF0066);
else
return (0xFF000066);
}
void draw_battery(mlx_image_t *img, float battery)
{
int x;
int y;
x = 1340;
while (x < 1350)
{
y = 265;
while (y < 285)
{
mlx_put_pixel(img, x, y, battery_color(battery));
y++;
}
x++;
}
x = 1350;
while (x < 1450)
{
y = 250;
while (y < 300)
{
mlx_put_pixel(img, x, y, battery_color(battery));
y++;
}
x++;
}
}
void handle_battery(t_game *game)
{
game->player->battery -= game->screen->mlx->delta_time / 50;
if (game->player->battery < 0)
game->player->battery = 0.001f;
draw_battery(game->screen->minimap, game->player->battery);
}
void handle_record(t_game *game)
{
static int flash = 0;
int x;
int y;
flash = (game->framecount / 30) % 2;
y = -15;
while (y <= 15)
{
x = -15;
while (x <= 15)
{
if (x * x + y * y <= 225)
{
if (flash)
mlx_put_pixel(
game->screen->hud, 1530 + x, 212 + y, 0xFF000055);
else
mlx_put_pixel(
game->screen->hud, 1530 + x, 212 + y, 0x00000066);
}
x++;
}
y++;
}
}
void game_loop(void *param)
{
t_game *game;
static int fps = 0;
game = (t_game *)param;
game->framecount++;
fps += (int)(1.f / game->screen->mlx->delta_time);
set_uniforms(game);
if (game->framecount % 20 == 0)
{
game->fps = (int)(fps / 20);
fprintf(stderr, "FPS: %d\n", fps / 20);
fps = 0;
}
player_update(game, game->screen->mlx->delta_time);
cast_rays(game);
render_map(game);
keyboard_update(game);
if (game->player->is_moving)
{
game->screen->img->instances[0].x = sin(game->framecount / 6.0) * 20;
game->screen->img->instances[0].y = cos(game->framecount / 3.0) * 10;
}
handle_battery(game);
handle_record(game);
}
void game_free(t_game *game)
{
if (game->screen)
{
mlx_delete_image(game->screen->mlx, game->screen->img);
mlx_close_window(game->screen->mlx);
mlx_terminate(game->screen->mlx);
free(game->screen);
}
if (game->player)
free(game->player);
if (game->map)
map_free(game->map);
if (game->keyboard)
free(game->keyboard);
free(game);
}
void game_terminate(t_game *game)
{
game_free(game);
exit(EXIT_SUCCESS);
}