kresty1
kresty1

Reputation: 11

Converting grid-based level in string form into a 2D array in C++?

I've been completely lost on this one for the past day or so so I hope some of you may be able to figure it out. So basically I have a string of a grid-based level that I want to convert to a 2D array of numbers, but the conversion is not working properly. Now I do know a two things:

  1. I am reading the txt file correctly and
  2. Through some testing I know that when I manually set the values, objects render where they should so it can't be that (I use OpenGL if in any way that's relevant).

Any and all help/feedback would be appreciated and thanks in advance!

The level txt file looks like this:

       0 
       0 
       0
       0
       0
       0
       0
00000000

But this is the output (it should align with the zero-es in the txt file).

The output I got

This is the code I use for the conversion (keep in mind that both xSize and ySize are 8):

levelDat = new char* [xSize];

int atIndex = 0;
for (int x = 0; x < xSize; x++) {
    levelDat[x] = new char[ySize];
    for (int y = 0; y < ySize; y++) {       
        if (level[atIndex] != '\n') {
            levelDat[x][y] = level[atIndex];
        }
        atIndex++;
    }
}

for (int x = 0; x < xSize; x++) {
    for (int y = 0; y < ySize; y++) {
        if (levelDat[x][y] != AIR) {
            blockDat.push_back(x * BLOCK_SIZE);
            blockDat.push_back(y * BLOCK_SIZE);
            switch (levelDat[x][y]) {
            case DIRT:
                blockDat.push_back(1);
                break;
            default:
                blockDat.push_back(0);
                break;
            }
        }
    }
}

Upvotes: 0

Views: 86

Answers (1)

kresty1
kresty1

Reputation: 11

Okay I fixed it. I changed level[atIndex] to row.push_back(level[y*xSize+x]) since I wasn't reading the level array in the correct order.

Upvotes: 1

Related Questions