Search code examples
javaarraysmatrixgreenfoot

Creating matrices Java


I have trouble creating a matrice for a game map design.

void prepareMatrix(int width, int height)
{
    room = new int[height][width];
    for(int i = 0; i < height; i++)
    {
        for(int j = 0; j < width; j++)
        {
            if(i < height/4)
            {
                room[i][j] = 2;
            }
            else if(j == 0 || j == --width)
            {
                room[i][j] = 1;
            }
            else if(i == --height)
            {
                room[i][j] = 1;
            }
            else
            {
                room[i][j] = 0;
            }
        }
    }
}

I want to create something like this: (1- Wall1, 2- wall2, 0-floor)

2 2 2 2 2 2
2 2 2 2 2 2
1 0 0 0 0 1
1 0 0 0 0 1
1 0 0 0 0 1
1 1 1 1 1 1

And I get this:

2 2 2 2 2 2 2 2 2 2 
2 2 2 2 2 2 2 2 2 2 
1 0 0 0 0 1 0 0 0 0 
1 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 

The matrice would be a blueprint for the map.


Solution

  • You are using --width and --height. It appears from the expected result that you want the 1's to go in the first and last columns and in the last row. As a commenter implied, --width does not just return the width minus one, it also reduces width by 1. You may want width - 1 and height - 1 instead.