Game Development – Nr.4 | Magic Writer
|
HighscoreManager This week i have been working on updating a previous version of our high score system. The first version of the system worked in three steps. The first step was to load a .txt file and read different scores such as ”1000” etc. The second step was to sort all of the scores with the highest score first. The third step was to add a new high score and check if the new score mad e it to the high score list. The new system works similar but with some different results. The new system works by connecting a score to a name. By having a struct called ScoreEntry i could easily connect a name and a score. This is how the struct looks like:
struct ScoreEntry
{
//Stores the users name
std::string name;
//Stores the users score
int score;
//Returns a string that connects the name and score as one string
std::string GetText()
{
return (name + " " + std::to_string(score));
}
};
So the highscore works by having a vector (a list) that holds X number of these ScoreEntry structs. The first element in the vector is equal to the player with highest score. By having them sorted in the vector it gets easier to draw all the user scores in score order later on. Loading the highscores
while (!file.eof())
{
ScoreEntry entry;
file >> entry.name;
file >> entry.score;
m_entries.push_back(entry);
}
Adding a new high score This is a short example of how this works…. (Not the full code for writing)
for (int i = 0; i < m_entries.size(); i++)
{
//Compare new entries score and the old ones
if (entry.score > m_entries[i].score)
{
//Add new score one step above the last score
m_entries.insert(m_entries.begin() + i, entry);
}
//Write entry to file
file << m_entries[i].name;
file << " " << m_entries[i].score;
}
Displaying the scores
for (int i = 0; i < m_entries.size(); i++)
{
m_text.setString(std::to_string(i + 1) + ". " + m_entries[i].GetText());
m_text.setPosition(m_position.x, m_position.y + i * 45);
drawManager->Draw(m_text, sf::RenderStates::Default);
}
The result is this |
