Sign in to follow this  
Phineas

Separating Drawing Code from Game Logic

Recommended Posts

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[i]->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!

Share this post


Link to post
Share on other sites
You could use the model-view-controller pattern, with the shape classes as your models, and the classes for drawing the shapes inheriting from an abstract ShapeView class:


class ShapeView
{
public:
virtual void draw() = 0;
};

class SquareView : public ShapeView
{
public:
SquareView(Square* square);

virtual void draw();

private:
Square* square;
};



This will effectively seperate drawing from logic. Check out wikipedia for more information on the model-view-controller pattern.

Share this post


Link to post
Share on other sites
I was going to suggest using the Visitor design pattern in order to have all the drawing code isolated in one single visitor class, but Hexus suggestion seems more appropriate to the case at hands. In wikipedia you can find information about both the model-view-controller and the visitor (and other) design patterns.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this