I'd like to separate my drawing code from my game logic. I'm using C++ and OpenGL. The following is a simplification of what I'm doing in my game.
So, in my game all my objects derive from a class called Shape. I want to have a list of Shape*'s so I can simply do the following to draw all the objects:
int i;
for (i = 0; i < 100; ++i)
{
shapes->draw();
}
The code for the base class Shape is:
class Shape
{
public:
virtual ~Shape();
virtual void draw() = 0;
protected:
double x, y; // position
};
Now, I have two derived classes, Square and Circle:
class Square : public Shape
{
public:
Square();
private:
double width;
};
class Circle : public Shape
{
public:
Circle();
private:
double radius;
};
I'd like to put the code for Shape, Square, and Circle in a separate library from my drawing code. What is the best way to do this?
The following are some ideas I came up with, but I'm not confident they're the best and cleanest way.
Method 1:
Give each derived class a function pointer, and at the beginning of the program set the function pointers to point to the appropriate drawing function. I also thought about making the function pointer a static member of each derived class.
Method 2:
Create my own DisplayList class that describes how to draw an object. It would have a list of vertices, colors, etc. to pass to OpenGL functions. I don't like this idea since it's complicated and I feel like I'm duplicating OpenGL display lists.
If you're curious, I want do this for
test-driven development, in which it is best to separate graphics from your game logic so you can test just the logic.
Thanks for your help!