-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHighscoreUnit.cpp
More file actions
63 lines (55 loc) · 1.61 KB
/
Copy pathHighscoreUnit.cpp
File metadata and controls
63 lines (55 loc) · 1.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include "HighscoreUnit.hpp"
#include "Utils.hpp"
#include <fstream>
#include <algorithm>
#include <filesystem>
std::string THighscore::GetFilePath() const {
std::string base = Utils::GetPersonalPath();
#ifdef _WIN32
return base + "\\thesheepkiller\\highscores.txt";
#else
return base + "/.thesheepkiller/highscores.txt";
#endif
}
void THighscore::AddScore(int score, const std::string& name) {
auto it = std::find_if(entries.begin(), entries.end(), [&](const THighscoreEntry& e) {
return e.name == name;
});
if (it != entries.end()) {
if (score > it->score) {
it->score = score;
} else {
return;
}
} else {
entries.push_back({score, name});
}
std::sort(entries.begin(), entries.end(), [](const THighscoreEntry& a, const THighscoreEntry& b) {
return a.score > b.score;
});
if (entries.size() > 10) entries.resize(10);
}
void THighscore::Load() {
entries.clear();
std::ifstream file(GetFilePath());
if (!file.is_open()) {
for(int i=0; i<10; ++i) entries.push_back({0, "no one"});
return;
}
int s;
std::string n;
while (file >> s >> std::ws && std::getline(file, n)) {
entries.push_back({s, n});
}
if (entries.empty()) {
for(int i=0; i<10; ++i) entries.push_back({0, "no one"});
}
}
void THighscore::Save() {
std::string path = GetFilePath();
std::filesystem::create_directories(std::filesystem::path(path).parent_path());
std::ofstream file(path);
for (const auto& e : entries) {
file << e.score << " " << e.name << "\n";
}
}