2d arrays.

Hi,
im having a problem when trying to draw an image multiple times to different screen co-ordinates i have saved in a 2d array.
(The 2d arrays holds 15 x 2 co-ordinates, this is for a battleship mobile game.)

This is the snippet of code im using to draw the image(s):

for (int i = 0; i < 15; i++)
for (int j = 0; j < 2; j++)
g.drawImage(HitImg, CursorHitForClient[i][j], CursorHitForClient[i][j], Graphics.HCENTER | Graphics.BOTTOM);

Anyone know how to do this???

Thanks,
Hopper

Lets say that you have a 3x2 array instead, for simplicity’s sake, that looks like this


0  0
0 10
0 20

meanig that you want the pictures to be drawn down the left hand side like this


[ ]
[ ]
[ ]

Ok, now lets look at your code


for (int i = 0; i < 3; i++)
{
    for (int j = 0; j < 2; j++)
    {
        g.drawImage(HitImg, CursorHitForClient[i][j], CursorHitForClient[i][j], Graphics.HCENTER | Graphics.BOTTOM);
    }
}

I added the brackets for clairity. Ok on the first loop through it gets [0,0] which is 0, so it draws at (0,0), then it hits the inner loop again and gets [0,1] which is 0 again so it draws another one at (0,0). The it hits the outer loop again and it it gets [1,0] which is 0, so it draws a third image at (0,0), then it gets [1,1] whic is 10, so it draws the image at (10, 10)!!! Then it will draw another one at (0,0) then at (20,20), then at (0,0) then at (30,30).

The trouble is that you are using the same value for both the X and Y coordinates of the drawImage(). Your code should look like this instead.


for (int i = 0; i < 3; i++)
{
    g.drawImage(HitImg, CursorHitForClient[i][0], CursorHitForClient[i][1], Graphics.HCENTER | Graphics.BOTTOM);
}

i think u need to change this line:

g.drawImage(HitImg, CursorHitForClient[i][j], CursorHitForClient[i][j], Graphics.HCENTER | Graphics.BOTTOM);

to

g.drawImage(HitImg, CursorHitForClient[i][0], CursorHitForClient[i][1], Graphics.HCENTER | Graphics.BOTTOM);

EDIT: i really should read properly b4 posting, cborders just explained this. ::slight_smile: