Search code examples
javaexportlwjglslick2d

More Efficient Way of making multiple objects


I am trying to make a memory game with Java. The game is basically going to be some squares in a grid that is 4x4 at the moment just for testing purposes. I have created my Square class, and programmed what i want them to do in that class, and then created a square object in another Class that handles the "Normal Mode" of the game. Now since i have a 4x4 grid of squares I need to make 16 different Squares (Or at least that's what i'm thinking at the moment). I also need to draw the Squares in their corresponding place.

My Question: What is the most efficient way of creating 16 of these Square objects while still being able to manipulate them individually? (Sort of like each having their own name; Square, Square1, Square2, etc).

I am also using the Slick2D library.


Solution

  • As mentioned above, Square[][] squareGrid = new Square[4][4] is a good way to go about this; then you can initialize all 16 of them using:

     for (int i = 0; i < squareGrid.length; i++)
            for(int j = 0; j < squareGrid[i].length; j++)
                squareGrid[i][j] = new Square();
    

    now each square automatically has its own unique (row, col) id. for example,

    squareGrid[1][2].callSomeFunctionInSquareClass();
    

    can be used to manipulate the square at 2nd row, 3rd column. This way you will avoid scanning through all the squares to get the one at a particular cell on the grid, thus making it much more efficient.

    happy coding :)