PCBrawl/src/bullet.c

84 lines
2.1 KiB
C

#include "bullet.h"
#include "conf.h"
#include "level.h"
#include "lzy.h"
#include "tools.h"
#include <stdlib.h>
#include <string.h>
static struct Bullet_table bullet_table;
static void bullet_table_free(void);
static void bullet_update(struct Bullet *bullet);
static void bullet_draw(struct Bullet *bullet, int timer);
void bullet_table_init(void) {
bullet_table_free();
bullet_table.bullets = malloc(MAX_BULLETS * sizeof(struct Bullet));
bullet_table.n = 0;
for (int i = 0; i < MAX_BULLETS; ++i) {
bullet_table.bullets[i].active = 0;
}
}
void bullet_table_free(void) {
if (bullet_table.bullets != NULL) {
bullet_table.bullets = NULL;
}
};
void bullet_fire(int x, int y, int dir_x, int dir_y, int v) {
for (int i = 0; i < MAX_BULLETS; ++i) {
if (!bullet_table.bullets[i].active) {
bullet_table.bullets[i] =
(struct Bullet){.pos = (struct Vec2){.x = x - 8, .y = y - 8},
.dir = (struct Vec2){.x = dir_x, .y = dir_y},
.v = v,
.active = 1};
break;
}
}
++bullet_table.n;
}
void bullet_table_update(void) {
for (int i = 0; i < MAX_BULLETS; ++i) {
if (bullet_table.bullets[i].active) {
bullet_update(&bullet_table.bullets[i]);
}
}
}
void bullet_update(struct Bullet *bullet) {
bullet->pos.x += bullet->dir.x * bullet->v;
bullet->pos.y += bullet->dir.y * bullet->v;
/* boom */
const struct Vec2 level_dim = level_get_dim();
if (bullet->pos.x < -72 || bullet->pos.x > level_dim.x * TILE_S + 48 ||
bullet->pos.y < -96 || bullet->pos.y > level_dim.y * TILE_S + 48) {
bullet_destroy(bullet);
}
}
void bullet_table_draw(int timer) {
for (int i = 0; i < MAX_BULLETS; ++i) {
if (bullet_table.bullets[i].active) {
bullet_draw(&bullet_table.bullets[i], timer);
}
}
}
void bullet_draw(struct Bullet *bullet, int timer) {
LZY_DrawTile(15, bullet->pos.x, bullet->pos.y);
}
void bullet_destroy(struct Bullet *bullet) {
bullet->active = 0;
--bullet_table.n;
}
int bullet_nb(void) { return bullet_table.n; }