-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsave.cpp
109 lines (97 loc) · 2.34 KB
/
save.cpp
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#include "save.h"
#include <fstream>
#include <algorithm>
#include <unistd.h>
int Save::readHighScore(std::string username)
{
for (record rec : listScores())
{
if (rec.username == username)
{
return rec.score;
}
}
return 0;
}
Save::record *Save::readHighScore()
{
std::ifstream in;
in.open("snake.save", std::ios::binary);
int score, size;
std::string username;
record *rec = new record;
if (in.read((char *)&score, sizeof(score)))
{
in.read((char *)&size, sizeof(size));
username.resize(size);
in.read((char *)&username[0], size);
*rec = {username, score};
}
else
{
*rec = {"", 0};
}
in.close();
return rec;
}
void Save::writeHighScore(std::string username, int score)
{
std::vector<record> records = listScores();
bool found = false;
for (int i = 0; i < records.size(); i++)
{
if (records[i].username == username)
{
found = true;
if (score > records[i].score)
{
records[i].score = score;
}
else
{
return;
}
break;
}
}
if (!found)
{
records.push_back({username, score});
}
std::sort(records.begin(), records.end(), comp);
std::ofstream out;
out.open("snake.save", std::ios::binary);
for (int i = 0; i < records.size(); i++)
{
out.write((char *)&records[i].score, sizeof(int));
int size = records[i].username.size();
out.write((char *)&size, sizeof(size));
out.write((char *)&records[i].username[0], size);
}
out.close();
}
std::vector<Save::record> Save::listScores()
{
std::ifstream in;
in.open("snake.save", std::ios::binary);
std::vector<record> records(0);
int score, size;
while (in.read((char *)&score, sizeof(score)))
{
in.read((char *)&size, sizeof(size));
std::string username;
username.resize(size);
in.read((char *)&username[0], size);
records.push_back({username, score});
}
in.close();
return records;
}
bool Save::record::operator<(const record other)
{
return this->score > other.score;
}
bool Save::comp(const Save::record &lhs, const Save::record &rhs)
{
return lhs.score > rhs.score;
}