summaryrefslogtreecommitdiff
path: root/src/hiscore.cc
blob: 971b84cd6d8152419d29fd9adf955c53dbe5c45c (plain)
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
#include "hiscore.hpp"

#include "util.hpp"

#include <cassert>

int highscore_seek(int highscore_fd, int i)
{
	/* Seek for the requested record */
	return (fd_seek(highscore_fd, (huge)(i) * sizeof(high_score)));
}

errr highscore_read(int highscore_fd, high_score *score)
{
	/* Read the record, note failure */
	return (fd_read(highscore_fd, (char*)(score), sizeof(high_score)));
}

int highscore_write(int highscore_fd, high_score *score)
{
	/* Write the record, note failure */
	return (fd_write(highscore_fd, (char*)(score), sizeof(high_score)));
}

int highscore_where(int highscore_fd, high_score *score)
{
	int i;

	high_score the_score;

	/* Paranoia -- it may not have opened */
	if (highscore_fd < 0) return ( -1);

	/* Go to the start of the highscore file */
	if (highscore_seek(highscore_fd, 0)) return ( -1);

	/* Read until we get to a higher score */
	for (i = 0; i < MAX_HISCORES; i++)
	{
		if (highscore_read(highscore_fd, &the_score)) return (i);
		if (strcmp(the_score.pts, score->pts) < 0) return (i);
	}

	/* The "last" entry is always usable */
	return (MAX_HISCORES - 1);
}

int highscore_add(int highscore_fd, high_score *score)
{
	int i, slot;
	bool_ done = FALSE;

	high_score the_score, tmpscore;


	/* Paranoia -- it may not have opened */
	if (highscore_fd < 0) return ( -1);

	/* Determine where the score should go */
	slot = highscore_where(highscore_fd, score);

	/* Hack -- Not on the list */
	if (slot < 0) return ( -1);

	/* Hack -- prepare to dump the new score */
	the_score = (*score);

	/* Slide all the scores down one */
	for (i = slot; !done && (i < MAX_HISCORES); i++)
	{
		/* Read the old guy, note errors */
		if (highscore_seek(highscore_fd, i)) return ( -1);
		if (highscore_read(highscore_fd, &tmpscore)) done = TRUE;

		/* Back up and dump the score we were holding */
		if (highscore_seek(highscore_fd, i)) return ( -1);
		if (highscore_write(highscore_fd, &the_score)) return ( -1);

		/* Hack -- Save the old score, for the next pass */
		the_score = tmpscore;
	}

	/* Return location used */
	return (slot);
}