Day 4 of the Level Editor project

Today we want to introduce saving and loading to our project. In game.h, we introduce these new variables:

unsigned int levelSizeX;
unsigned int levelSizeY;
Keys *keyPressed;

keyPressed stores keys that have been detected as pressed, so that we can perform an action as soon as the key is released. In the Initialize method of game.cpp, we initialize keyPressed:

  keyPressed = new Keys();

Now we have to append the following code to the Update method so that the action is performed once the respective key is released:

if (g_keys->keyDown['S'])
{
keyPressed->keyDown['S'] = true;
}
else if (keyPressed->keyDown['S'] && !g_keys->keyDown['S'])
{
SaveLevel();
keyPressed->keyDown['S'] = false;
}

if (g_keys->keyDown['L'])
{
keyPressed->keyDown['L'] = true;
}
else if (keyPressed->keyDown['L'] && !g_keys->keyDown['L'])
{
LoadLevel();
keyPressed->keyDown['L'] = false;
}

For now, let's define SaveLevel as:

void Game::SaveLevel()
{
std::ofstream file;
file.open("level0.sav");
file.write((const char *) &levelSizeX, sizeof(unsigned int));
file.write((const char *) &levelSizeY, sizeof(unsigned int));
for (auto const& i : level) 
{
file.write((const char *) &i->type, sizeof(LevelEditorDrawModes));
file.write((const char *) &i->coordX0, sizeof(unsigned int));
file.write((const char *) &i->coordY0, sizeof(unsigned int));
file.write((const char *) &i->coordX1, sizeof(unsigned int));
file.write((const char *) &i->coordY1, sizeof(unsigned int));
}
file.close();
}

And LoadLevel:

void Game::LoadLevel()
{
std::ifstream file;
file.open("level0.sav");
file.read((char *)&levelSizeX, sizeof(unsigned int));
file.read((char *)&levelSizeY, sizeof(unsigned int));
level.clear();
while (file.peek() != EOF)
{
LevelDrawElement *i = new LevelDrawElement();
file.read((char *)&i->type, sizeof(LevelEditorDrawModes));
file.read((char *)&i->coordX0, sizeof(unsigned int));
file.read((char *)&i->coordY0, sizeof(unsigned int));
file.read((char *)&i->coordX1, sizeof(unsigned int));
file.read((char *)&i->coordY1, sizeof(unsigned int));
level.push_back(i);
}
file.close();
}

We already have a very simple but useable level editor. The basic stuff is done. Now the next steps will be to enhance the functionality, so that we can define the size of the level in pixels, place the player, place the enemies, etc.

Kommentare

Beliebte Posts aus diesem Blog

The Demoscene

Digital Art Natives

Autobiographical Sketch