From 0c820ace5a4688b68849fb149811fb7331e53f78 Mon Sep 17 00:00:00 2001 From: "Juan J. Martinez" Date: Tue, 27 Jun 2023 21:49:22 +0100 Subject: Add Bat enemy --- src/bat.c | 94 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/bat.h | 7 +++++ src/entities.h | 2 +- src/map.c | 2 ++ 4 files changed, 104 insertions(+), 1 deletion(-) create mode 100644 src/bat.c create mode 100644 src/bat.h (limited to 'src') diff --git a/src/bat.c b/src/bat.c new file mode 100644 index 0000000..73ea4b2 --- /dev/null +++ b/src/bat.c @@ -0,0 +1,94 @@ +#include + +#include +#include "map.h" +#include "entities.h" + +#include "player.h" + +#include "bat.h" + +#define DIR_UP 0 +#define DIR_DOWN 1 + +/* limit of the animation cycle */ +#define MAX_FRAME 4 + +static const Rect frames[2 * 4] = +{ + /* right */ + { 64, 32, 144, 144 }, + { 80, 32, 144, 144 }, + { 96, 32, 144, 144 }, + { 80, 32, 144, 144 }, + + /* left */ + { 64, 32, 144, 144 }, + { 80, 32, 144, 144 }, + { 96, 32, 144, 144 }, + { 80, 32, 144, 144 }, +}; + +void bat_init(Entity *e) +{ + e->frames = (const Rect *)frames; + e->update = bat_update; + /* will control vertical movement */ + e->flags = DIR_UP; +} + +void bat_update(Entity *e) +{ + if (e->delay & 1) + { + /* horizontal */ + if (e->dir == DIR_RIGHT) + { + if (map_is_blocked(e->x + 16, e->y + 7)) + e->dir = DIR_LEFT; + else + e->x++; + } + else + { + /* dir is LEFT */ + if (map_is_blocked(e->x - 1, e->y + 7)) + e->dir = DIR_RIGHT; + else + e->x--; + } + + /* vertical */ + if (e->flags == DIR_DOWN) + { + if (map_is_blocked(e->x + 7, e->y + 16)) + e->flags = DIR_UP; + else + e->y++; + } + else + { + /* dir is UP */ + if (map_is_blocked(e->x + 7, e->y - 1)) + e->flags = DIR_DOWN; + else + e->y--; + } + } + + if (player_collision(e)) + { + player_hit(); + /* change direction */ + e->dir ^= 1; + e->flags ^= 1; + } + + if (e->delay++ == WALK_DELAY - 2) + { + e->delay = 0; + e->frame++; + if (e->frame == MAX_FRAME) + e->frame = 0; + } +} diff --git a/src/bat.h b/src/bat.h new file mode 100644 index 0000000..cf21e8a --- /dev/null +++ b/src/bat.h @@ -0,0 +1,7 @@ +#ifndef _BAT_H +#define _BAT_H + +void bat_init(Entity *e); +void bat_update(Entity *e); + +#endif /* _BAT_H */ diff --git a/src/entities.h b/src/entities.h index e553390..016dcd2 100644 --- a/src/entities.h +++ b/src/entities.h @@ -15,7 +15,7 @@ typedef struct entity_s uint8_t frame; uint8_t delay; uint8_t gravity; - uint8_t flag; + uint8_t flags; uint8_t bg[16 * 16]; /* expected to be 2 directions per 4 frames max; 8 Rect */ const Rect *frames; diff --git a/src/map.c b/src/map.c index c62c5c1..f7c271b 100644 --- a/src/map.c +++ b/src/map.c @@ -9,6 +9,7 @@ #include "entities.h" #include "player.h" #include "snake.h" +#include "bat.h" #include "map.h" @@ -26,6 +27,7 @@ static uint8_t total_gold; static void (* const init[])(Entity *) = { snake_init, + bat_init, }; void map_init(const uint8_t map[]) -- cgit v1.2.3