I'm creating a map editor for a game project. My method of mapping is having a large 2D array of chars(map[300][300];). For different types of tiles, I simply set map[x][y] to a different value. I then use a function in the drawing/collision(inside of the game's client) to determine what type of tile it is, what to draw, and if it is blocked or not. I have saving/loading maps finished. My problem is having only 10 tiles available - 0-9. If I create a 10th tile and still write it to the file, when I load it into the game/editor it will first read the '1' then the '0' which wouldn't be correct.
Is it possible to read two digits at a time from a file using something such as file >> map[x][y];? If not, what other type of method can I use? For I cannot make one char out of two chars.. I'm just kind of confused at the moment. Any help will be appreciated. Thank you!
Ah, alright. I tried doing that, however nothing is being written into the file except for spaces... I have also made map[300][300] unsigned chars so map[x][y] is able to hold values up to 255.
This is my saving code... Everything seems fine to me. :S
1 2 3 4 5 6 7 8 9 10 11 12 13
void save(unsignedchar map[300][300]) {
ofstream file;
file.open ("dat001.dat");
for (int x = 0; x < 300; x++) {
for (int y = 0; y < 300; y++) {
file << map[x][y];
file << " ";
}
}
file.close();
}
This is my loading code, although it's pretty much the same thing as the text you have supplied above.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
void load(unsignedchar map[300][300]) {
ifstream file;
file.open ("dat001.dat");
int i;
for (int x = 0; x < 300; x++) {
for (int y = 0; y < 300; y++) {
if(file >> i) map[x][y] = i;
}
}
file.close();
}
I would not use text files for this. This is much simpler if you store the file as binary. Open the file as ios_base::binary and use read() and write() instead of << and >>:
Alright, I started storing the file as binary. Also, I have gotten tile types more than 10 working as well.. I was saving ints into the file instead of chars. Since 10 will be represented by an ASCII character, it will read 10 as a char and then load that into the map's array. It was a mix of me being stupid, and a slight logic error.