# Space invaders 2d array to represent scene [duplicate]

For code optimization purposes, I want to create a 2d array that contains 40 equal squares (10x10px). Each square represents 1\40 of the displayed window (400x400px).

I populate the 2d array with the standard double for-loop methodology.

    int col = 40;
int row = 40;
int boxSize = 0;
Integer[][] boxes = new Integer;

for (int i = 0; i < col; i++) {
for (int j = 0; j < row; j++) {
boxes[i][j] = boxSize;
boxSize += 10; //Creates a 10px box.
}
boxSize = 0; //Resets box size for next column
}


There are several circles in this program. We have a ship(circle) that fires missiles(circles) toward enemies(circles).

I want to run collision detection ONLY when there is a bullet + an enemy in one of the squares. This will greatly optimize the code.

The question is... how do I create these squares off of a 2d array? How do I select each square? How do I test if the missiles and the enemies are inside the same square?

Thanks.

• You need to remember that a circle can be in 4 or more squares in the same time. Jan 30, 2014 at 19:15
• Two things. 1. Because the screen is 400x400px and each square is 10x10px, each square actually represents 400^2 / 10^2 = 1/1,600 of the screen. 2. I am trying to figure out why each array element stores a number that increases with the y axis (I am refering to the line that says boxSize += 10. All you have is an array that looks like this: "0, 10, 20, 30, 40, ..." and then goes back to zero at the start of each column. If you could answer this for me, it would be a lot easier to help you. Jan 31, 2014 at 0:00
• @AidanMueller I am confused and I do not know how to represent the squares and actually connect them to the elements(circles) on the screen to know what their location is. Jan 31, 2014 at 13:20
• Check my new thread with more details about the problem please: gamedev.stackexchange.com/questions/69686/… Feb 1, 2014 at 9:06