问题描述
我正在尝试用Java进行内存游戏。这个游戏基本上将是一个4x4的网格中的一些正方形,用于测试目的。我创建了我的Square类,并编程了我想要他们在该类中做的事情,然后在另一个类中创建一个方形对象,处理游戏的正常模式。现在,因为我有一个4x4格子的广场,我需要做16个不同的正方形(或至少这就是我现在在想的)。我也需要在相应的地方绘制正方形。我的问题:创建16个Square对象的最有效的方法是什么,同时还能够单独操作? (每个都有自己的名字的排序; Square,Square1,Square2等)。
我也使用Slick2D库。
如上所述,Square [] [] squareGrid = new Square [4] [4]是一个很好的办法;
然后您可以使用以下方式初始化所有16个:
for(int i = 0; i< squareGrid。长度; i ++)
for(int j = 0; j< squareGrid [i] .length; j ++)
squareGrid [i] [j] = new Square();
现在每个Square都有自己的唯一(row,col)id。例如
squareGrid [1] [2] .callSomeFunctionInSquareClass();
可用于操作第二行,第三列的平方。
这样,您将避免扫描所有正方形,以获得网格上特定单元格的方格,从而使其效率更高。
快乐编码:)
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 :)
这篇关于更高效的制作多个对象的方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!