Explanation of the enemies.h
and enemies.c System
These two files work together to define, create, and update
all enemy sprites in the game.
The header file (enemies.h) declares the
variables and functions that other parts of the program can use, while the source
file (enemies.c) contains the actual logic that
spawns enemies and updates their movement each frame.
1. enemies.h — Interface and
Declarations
enemies.h provides the public interface for the enemy system. It declares:
Enemy sprite pointers
extern Sprite* fly;
extern Sprite* snail;
extern Sprite* bee;
extern Sprite* crab;
These point to the actual sprite objects after they are created. Other files can reference these pointers if needed (e.g., for collisions).
Position and velocity arrays
extern fix32 enemy_x[4];
extern fix32 enemy_velx[4];
extern fix32 enemy_y[4];
These arrays store each enemy’s X position, Y position, and
horizontal movement speed.
Index meaning:
Functions
extern void createEnemies();
extern void manageEnemies();
The header protects itself with include guards to prevent multiple-inclusion issues.
2. enemies.c — Implementation
of Enemy Logic
enemies.c defines and initializes the data declared in the header.
Static enemy data initialization
The four enemies start with hard-coded positions and velocities:
enemy_x = {50, 30, 70, 90}
enemy_y = {80, 40, 120, 180}
enemy_velx = {1.5, -0.5, 2, -0.5}
This means each enemy will move horizontally at a different speed and direction.
2.1. createEnemies() — Spawns the enemy sprites
This function:
Each sprite is also assigned a palette and tile attributes.
2.2. manageEnemies() — Updates movement every frame
This function performs two things:
A. Movement update
Every enemy’s X coordinate is updated by its velocity:
enemy_x[i] += enemy_velx[i];
B. Sprite repositioning
After updating the logic data, the function applies the new positions to the actual sprites:
SPR_setPosition(fly, fix32ToInt(enemy_x[0]), fix32ToInt(enemy_y[0]));
SPR_setPosition(snail, ... );
SPR_setPosition(bee, ... );
SPR_setPosition(crab, ... );
This is what makes the enemies visually move on the screen.