Reputation: 4078
I'm making a simple tic tac toe game as an exercise in LWJGL.
When I write methods to draw the board squares and pieces such as the x and o pieces, should I put them in one graphicsLib class that can then be called by the various objects such as the board? or is it considered best practice to have each object contain the code to draw its own element? I'm looking to make the code as extensible as possible.
Specifically, I have a Board class which is a collection of objects of type Square, and the square objects are assigned an enum state CLEAR, X, or O. I then run a switch statement on the state that will call the appropriate method to draw the square. Should I put each method in its own object or have one large graphics object (say public class graphicsLib) that then supplies the methods to draw the various elements?
What is the best way to organize this?
Upvotes: 1
Views: 346
Reputation: 10473
Where possible, use an object-oriented approach when you can. When I'm writing something like this, I would generally have each of my objects provide at least two methods:
public void update(int delta);
public void render();
That way my objects and the many instantiations of them all know how to update themselves and render themselves. You could then structure your code such that your Board class's update and render methods will call update
and render
on its children Squares (See example below). This provides some benefits:
render
method.Here's the example of the hierarchy rendering.
public class Board {
List<Square> squares;
public render() {
// Render your board first
...
// Render child squares
for (Square square : squares) {
square.render();
}
}
}
So as you could imagine, your main game loop could simply tell your board object to render and you're done. You don't need to have any intimate knowledge of what else the board might need to render.
Upvotes: 1