sakurashinken
sakurashinken

Reputation: 4078

Organizing code in LWJGL

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

Answers (1)

Marc Baumbach
Marc Baumbach

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:

  1. Drawing/updating of objects is cohesively close to the representation of that object (Separation of concerns).
  2. As your "model" classes become complex, your rendering functions are close to that data, so your APIs stay stable. If you had one class for drawing, you could imagine you'd have to pass a lot of data to the drawing class and each of those calls would have to be customized and changed as your model changes.
  3. You won't have one gigantic class that provides an API for drawing everything. This would become large and unwieldy quickly.
  4. You have a built-in structure for the Painter's Algorithm since your have a hierarchy of when things are drawn based on a parent/child relationship. You only need to manage your siblings correctly at each parent's 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

Related Questions