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.
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 :)
You can try Square[][] grid = new Square[4][4]
I would use a Square[][] array, e.g. Square[][] squares = new Square[4][4]
, and then initialise it with all 16 Squares in two nested loops:
for (int x = 0; x < squares.length) x++)
for (int y = 0; y < squares[x].length; y++)
squares[x][y] = new Square(x, y);