Hello everyone this is my code in my main.cpp and I am trying to create an array for the enemies instead of writing 44 of them like this. What would you suggest me to do or how can I create an array of this. I need to create 44 enemies with 3 different colors.
Enemy red_enemy1(
windowWidth / 2 - 16, // x
windowHeight - 400, // y
"images/GalaxianRedAlien.gif");
Enemy red_enemy2(
windowWidth / 2 - 16 34, // x
windowHeight - 400,
"images/GalaxianRedAlien.gif");
Enemy red_enemy3(
windowWidth / 2 - 16 64, // x
windowHeight - 400,
"images/GalaxianRedAlien.gif");
// create a blue enemy
Enemy blue_enemy1(
windowWidth / 2 - 16, // x
windowHeight - 400 32, // y
"images/GalaxianAquaAlien.gif");
CodePudding user response:
use std::vector
std::vector<Enemy> enemies;
enemies.emplace_back(
windowWidth / 2 - 16, // x
windowHeight - 400, // y
"images/GalaxianRedAlien.gif");
enemies.emplace_back(
windowWidth / 2 - 16 34, // x
windowHeight - 400, // y
"images/GalaxianRedAlien.gif");
etc
you can now refer to enemies[0]
...
CodePudding user response:
If Enemy is an aggregate/POD type, you could do it like this:
struct Enemy
{
int x;
int y;
const char * gifName;
};
int windowWidth = 640;
int windowHeight = 640;
Enemy red_enemies[] =
{
{ windowWidth / 2 - 16, windowHeight - 400, "images/GalaxianRedAlien.gif" },
{ windowWidth / 2 - 16 34, windowHeight - 400, "images/GalaxianRedAlien.gif" },
{ windowWidth / 2 - 16 64, windowHeight - 400, "images/GalaxianRedAlien.gif" }
};
However, raw/C-style arrays are non-resizable, so if you're planning to support a variable number of enemies, you'll be much better off if you use a proper data structure like std::vector<Enemy>
instead:
#include <vector>
class Enemy
{
public:
Enemy() : _x(0), _y(0), _gifName(NULL) {}
Enemy(int x, int y, const char * gifName) : _x(x), _y(y), _gifName(gifName) {}
int _x;
int _y;
const char * _gifName;
};
int main(int, char **)
{
int windowWidth = 640;
int windowHeight = 640;
std::vector<Enemy> enemies;
for (int i=0; i<3; i ) enemies.push_back(Enemy((windowWidth/2)-16 (i*32), windowHeight-400, "images/GalaxianRedAlien.gif"));
return 0;
}