Zastanawiam się nad wczytywaniem jednostek z pliku do programu,obecna konstrukcja mi się nie podoba,myślę że da się to zrobić lepiej a ja to za bardzo zagmatwałem, i takie wczytywanie powoduje duże ryzyko wystąpienia błędów, możecie coś poradzić'? Oto mój kod:
Plik txt.
Load=[Creature][PositionX][PositionY]
[Slime][100][100]
[Slime][200][200]
[Slime][300][300]
Plik File Manager
enum LoadState { ATTRIBUTES, CONTENTS };
int state;
void FileManager::LoadContent(const char* filename, std::vector<std::vector<std::string>>& attributes,
std::vector<std::vector<std::string>>& contents)
{
attributes.clear();
contents.clear();
std::ifstream openfile(filename);
if (openfile.is_open())
{
while (!openfile.eof())
{
std::string line;
std::getline(openfile, line);
line.erase(std::remove(line.begin(), line.end(), ' '), line.end());
if (line.find("Load=") != std::string::npos)
{
state = ATTRIBUTES;
line.erase(0, line.find('=') + 1);
tempAttributes.clear();
}
else
{
state = CONTENTS;
tempContents.clear();
}
line.erase(std::remove(line.begin(), line.end(), '['), line.end());
std::stringstream str(line);
while (str)
{
std::getline(str, line, ']');
if (line != "")
{
if (state == ATTRIBUTES)
tempAttributes.push_back(line);
else
tempContents.push_back(line);
}
}
if (state == CONTENTS && tempContents.size() > 0)
{
attributes.push_back(tempAttributes);
contents.push_back(tempContents);
}
}
}
else
{
}
}
Fragment kodu gdzie wczytuje dane do programu:
characterType.insert(std::make_pair("Slime", Character::Slime));
file.LoadContent("level0.txt", attributes, contents);
for (int i = 0; i < attributes.size(); i++)
{
for (int j = 0; j < attributes[i].size(); j++)
{
std::string att = attributes[i][j];
std::string con = contents[i][j];
if (att == "Creature")
{
std::map<std::string, Character::Type>::iterator it = characterType.begin();
while (it != characterType.end())
{
if (it->first == contents[i][j])
{
std::unique_ptr<Character> enemy(new Character(it->second, mTextures));
mSceneLayers[Upper]->attachChild(std::move(enemy));
}
it++;
}
}
}
}
}
W tym fragmencie nie przypisuje pozycji jednostce. Mógłbym zrobić tak że: If att == PositionX then etity[entity.size()-1].position.x = contents[i][j]. Ale co jak powstaną potem inne elementy entity,nie tylko potwory ale tez kafelki. To wszystko dałoby się "JAKOŚ" zrobić ale to strasznie potem jest namieszane. Nie wiem czy obrałem zły sposób wczytywania tego wszystkiego czy coś, ale prosiłbym o jakiś wzorzec,pomysł. Plik txt będzie wyglądał tak:
Load=[Creature][PositionX][PositionY]
[Slime][100][100]
[Slime][200][200]
[Slime][300][300]
Load=[Tile][PositionX][PositionY][Move]
[Dirt][100][100][0]
[Stone][100][100][1]
Staram się to jakoś rozwiązać ale ciągle mnie to niesatysfakcjonujące,ktoś może mi dać jakiś pomysł,artykuł, cokolwiek?