Page 1 of 1
reading in maps
Posted: Sat Mar 20, 2010 11:32 pm
by Donutslayer7
Can you use fstream to read values into a 2D array? I have one tile array and one object array, and want to have my map values saved in text(or binary) files external to the application, then read them into the tile and object array when you reach a point on the current map.
On a different train of thought, could I use a scripting language instead of just using fstream to declare and set the values of a 2D array in a script?
Re: reading in maps
Posted: Sun Mar 21, 2010 12:40 am
by Maevik
Absolutely, you could do either one, although using a scripting language would be a lot more involved. How you do it is really up to you and depends heavily on how your program is designed. A basic way of doing it however would be setting up your file so that each line is a tag (text string) followed by a value.
IE:
levelName The Alabaster Citadel
musicTrack Vengence.mp3
background marbleCollumns.png
Then create a function to read in the file like:
Code: Select all
while( !fin.eof() )
// my phone doesnt seem to do curly braces :(
{ //ha! found it
string tag;
fin >> tag;
switch( tag )
case "background":
string bgName;
fin >> bgName;
// code to set the background image to the file named
break;
.
.
.
}
Youre also going to want to add extensive error checking as well for this type of thing.
hope this helps :D
Re: reading in maps
Posted: Sun Mar 21, 2010 7:50 am
by K-Bal
Re: reading in maps
Posted: Sun Mar 21, 2010 10:35 am
by avansc
Code: Select all
#include <fstream>
#include <stdio.h>
using namespace std;
class map
{
public:
map();
void printData();
private:
int data[10][10];
};
map::map()
{
for(int y = 0;y < 10;y++)
for(int x = 0;x < 10;x++)
this->data[y][x] = 10*y + x;
}
void map::printData()
{
for(int y = 0;y < 10;y++)
for(int x = 0;x < 10;x++)
printf("%d,%s", this->data[y][x], x == 9 ? "\n" : " ");
}
void saveMap(map *data, char *fileName)
{
ofstream ofs(fileName, ios::binary);
ofs.write((char*)data, sizeof(map));
ofs.close();
}
map *loadMap(char *fileName)
{
map *temp = (map*)malloc(sizeof(map));
ifstream ifs(fileName, ios::binary);
ifs.read((char*)temp, sizeof(map));
ifs.close();
return temp;
}
int main(void)
{
map *saveME = new map();
saveME->printData();
saveMap(saveME, "test.map");
map *test = loadMap("test.map");
test->printData();
getchar();
return 0;
}
Re: reading in maps
Posted: Sun Mar 21, 2010 8:07 pm
by Donutslayer7
Ah, I've seen the tag type structure used in the Source engine, all the tags were inside of scripts, and I kind of understand the code, but I'm not very familiar with the eof function(it looks very useful though). I guess I'll have to look more into fstream or some scripting language and look back at these examples.