2
\$\begingroup\$

Tilemap data is stored in a 2D array.

It is saved using the following code


void Chunk::save_to_file() {
    
    // FILENAME
    std::string filename = std::to_string(chunk_seed);

    std::fstream file;
    file.open(filename + ".chunk", std::ios::out);

    for (int i = 0; i < Constants::BIOMESIZE; i++) {
        for (int j = 0; j < Constants::BIOMESIZE; j++) {
            file << std::to_string(chunk[i][j]);
            file << ",";
        }
    }

    file.close();
    
}


And it is loaded using the following code


void Chunk::load_from_file() {
    // FILENAME
    // The chunk will be located at hash(chunk_x, chunk_y) ^ seed = chunk_seed
    std::string filename = std::to_string(chunk_seed);
    // Data within file
    std::string data;

    std::fstream file;
    file.open(filename + ".chunk", std::ios::in);
    file >> data;
    file.close();

    std::vector<std::string> tokens = split(data, ',');
    
    for (unsigned int i = 0; i < Constants::BIOMESIZE; i++) {
        for (unsigned int j = 0; j < Constants::BIOMESIZE; j++) {
            chunk[i][j] = std::stoi(tokens[i + j * Constants::BIOMESIZE]);
        }
    }
}

Tilemaps are loaded using the loading function when the program is started up and displayed.

Tilemaps are saved using the saving function when the program is exited.

They do not display the same way each time.

I have pinpointed that the problem is in the saving function.

This is because I commented out the saving part and when I was only loading the same files it worked and had the same output each time.

It appears as though the saving function rotates the tilemap by 180 degrees each time I save it.

How can this be fixed?

\$\endgroup\$
0

1 Answer 1

2
\$\begingroup\$

The rotation comes from the calculation of the index in load_from_file(), it should be:

chunk[i][j] = std::stoi(tokens[i * Constants::BIOMESIZE + j]);

That said, it would be much better if you could save the file in such a way that you can load it back the same way. Instead of using "," as a separator, use a space (" "). Then you can read it in like so:

std::ifstream file(filename + ".chunk");

for (unsigned int i = 0; i < Constants::BIOMESIZE; i++)
    for (unsigned int j = 0; j < Constants::BIOMESIZE; j++)
        file >> chunks[i][j];
```
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .