-
Notifications
You must be signed in to change notification settings - Fork 0
/
highscore.c
63 lines (55 loc) · 1.44 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
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "highscore.h"
/*
* TODO: Linked list for high score entry?
* Makes insertion easier.
*/
void loadhs() {
FILE *hsfile = fopen("highscores.txt", "rb");
// Construct entries if no file found
if (hsfile == NULL) {
char *name = malloc((NAMELEN+1)*sizeof(char));
for (int i=0; i<NAMELEN; i++) {
name[i] = '~';
}
name[NAMELEN] = '\0';
for (int i=0; i<NSCORES; i++) {
memcpy(highscores[i].name, name, NAMELEN+1);
highscores[i].score = 0;
}
free(name);
} else {
for (int i=0; i<NSCORES; i++) {
fscanf(hsfile, "%s %i\n", highscores[i].name, &highscores[i].score);
}
fclose(hsfile);
}
}
void iniths() {
highscores = malloc(NSCORES*sizeof(hsentry));
loadhs();
}
void savehs() {
FILE *hsfile = fopen("highscores.txt", "wb");
for (int i=0; i<NSCORES; i++) {
fprintf(hsfile, "%s %i\n", highscores[i].name, highscores[i].score);
}
fclose(hsfile);
}
void addhsentry(char name[NAMELEN], int score) {
for (int i=0; i<NSCORES; i++) {
if (score >= highscores[i].score) {
int buffsize = (NAMELEN-i-1)*sizeof(hsentry);
hsentry *buffer = malloc(buffsize);
memcpy(buffer, &highscores[i], buffsize);
memcpy(highscores[i].name, name, NAMELEN+1);
highscores[i].score = score;
memcpy(&highscores[i+1], buffer, buffsize);
free(buffer);
savehs();
break;
}
}
}