I am designing an AnimatedSprite class with SDL. AnimatedSprite contains a
vector of vectors of pointers to Sprite objects (that's because Sprite doesn't define the copy-constructor).
std::vector<std::vector<Sprite*>> spr_vec;
The AnimatedSprite class contains these 2 functions (now):
// creates an new Sprite set and returns its index
Uint16 CreateSet(Uint16 initialSize = 0);
// add a sprite to a SpriteSet
Uint16 AddSprite(Uint16 spriteSetOffset, const std::string &spriteFileName);
I am using a 2D vector because let's say I want to create an animated dog sprite.
// dog is an AnimatedSprite object
Uint16 dogMoveForwardOffset = dog.CreateSet();
Uint16 dogMoveBackwardsOffset = dog.CreateSet();
This way I have the forward and backward Sprites in different places, so I can easily access them.
The problem is with AddSprite.
Uint16 AnimatedSprite::AddSprite(Uint16 spriteSetOffset, const string &spriteFileName)
{
// if the offset exists in the vector
if(spriteSetOffset < spr_vec.size() )
{
spr_vec[spriteSetOffset].push_back(new Sprite(spriteFileName));
return spr_vec[spriteSetOffset].size() - 1;
}
}
If
spriteSetOffset is a valid vector position of spr_vec, everything is cool. But what if it isn't? I can't make it return 0 because 0 is valid offset.
I was thinking of changing the
return value to:
a) Sint16 or
b) const Sint16 (force a constant int to avoid changes)
so I can return
-1.
Another idea was to use a single vector and the user would have to keep himself the offset of where forward Sprites begin and end. I think my current design is better. What do you think?
Thanks in advance.
Better?
int AnimatedSprite::CreateSet(int initialSize)
{
if(initialSize < 0)
return -1;
// add a new set
spr_vec.push_back(vector <Sprite*>() );
// initial size
spr_vec.reserve(initialSize);
// return index
return spr_vec.size() - 1;
}
int AnimatedSprite::AddSprite(int spriteSetOffset, const string &spriteFileName)
{
// if the offset exists in the vector
if(spriteSetOffset >= 0 && spriteSetOffset < spr_vec.size() )
{
spr_vec[spriteSetOffset].push_back(new Sprite(spriteFileName));
return spr_vec[spriteSetOffset].size() - 1;
}
return -1;
}