So far, you needed to define all global objects at the top of your application file. This is OK for a little exercise, but when your project grows in size, this becomes a problem. You also have to know upfront how many objects you need. Even for a little game like asteroids, it is impossible to know how many rocks there will be on the screen at all times.
When you need several objects of the same type, you can use a container. When you declare a container for a certain object type, you can add objects to this container during the course of the application. An easy to use container is Memc. The declaration of a container requires that you provide the type of objects it will contain. When you need a container for floats, you would declare it as a Memc<float>. A container for rectangles would be a Memc<Rect>. Look at this code for an example of a container with circles:
// Declare a container for circles
Memc<Circle> circles;
void InitPre()
5{
EE_INIT();
}
bool Init()
10{
// add 10 circles to this container
for(int i = 0; i < 10; i++)
{
// The method New() adds a new circle to the container.
15 // At the same time the Circle method set() is used to
// assign a radius and a position.
circles.New().set(0.1, RandomF(-D.w(), D.w())
, RandomF(-D.h(), D.h())
);
20 }
return true;
}
void Shut() {}
25
bool Update()
{
if(Kb.bp(KB_ESC)) return false;
return true;
30}
void Draw()
{
D.clear(BLACK);
35
// Go over all circles in the container and
// draw them on the screen.
for(int i = 0; i < circles.elms(); i++)
{
40 circles[i].draw(RED);
}
}