forked from 0xminik/ctris
-
Notifications
You must be signed in to change notification settings - Fork 0
/
highscore.c
95 lines (86 loc) · 2.03 KB
/
highscore.c
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
#include "ctris.h"
#include "highscore.h"
void init_highscore(struct highscore_struct *highscore)
{
unsigned char i;
for(i = 0; i < 10; i++)
{
highscore->entry[i].score = 0;
highscore->entry[i].name[0] = '\0';
highscore->entry[i].time = 0;
}
}
char read_highscore(struct highscore_struct *highscore)
{
FILE *highscore_file;
if((highscore_file = fopen(highscore_file_path, "r")) == NULL)
{
init_highscore(highscore);
return 1;
}
size_t records = fread(highscore, sizeof(struct highscore_struct), 1, highscore_file);
fclose(highscore_file);
if (records == 0) {
return 1;
}
return 0;
}
void sort_entries(struct highscore_struct *highscore)
{
struct highscore_struct sorted_highscore;
unsigned char i, n, highest = 0;
unsigned int max;
for(i = 0; i < 10; i++)
{
max = 0;
for(n = 0; n < 10; n++)
{
if(highscore->entry[n].score > max)
{
max = highscore->entry[n].score;
highest = n;
}
}
memcpy(&sorted_highscore.entry[i], &highscore->entry[highest], sizeof(struct entry_struct));
highscore->entry[highest].score = 0;
highscore->entry[highest].name[0] = '\0';
highscore->entry[highest].time = 0;
}
memcpy(highscore, &sorted_highscore, sizeof(struct highscore_struct));
}
char write_highscore(struct highscore_struct *highscore)
{
FILE *highscore_file;
sort_entries(highscore);
if((highscore_file = fopen(highscore_file_path, "w")) == NULL)
{
return 1;
}
fwrite(highscore, sizeof(struct highscore_struct), 1, highscore_file);
fclose(highscore_file);
return 0;
}
char add_to_highscore(const char *name, const unsigned int score)
{
struct highscore_struct highscore;
if(in_highscore(score) != 0)
{
return 1;
}
read_highscore(&highscore);
highscore.entry[9].score = score;
highscore.entry[9].time = time(NULL);
strncpy(highscore.entry[9].name, name, 40);
write_highscore(&highscore);
return 0;
}
char in_highscore(const unsigned int score)
{
struct highscore_struct highscore;
read_highscore(&highscore);
if(score > highscore.entry[9].score)
{
return 0;
}
return 1;
}