20130313
[gdash.git] / src / cave / helper / cavehighscore.cpp
blobad72175010cc6531312bde26f0045b17251592e9
1 /*
2 * Copyright (c) 2007-2013, Czirkos Zoltan http://code.google.com/p/gdash/
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 #include "config.h"
19 #include <algorithm>
20 #include "cave/helper/cavehighscore.hpp"
22 /// Check if the achieved score will be put on the list.
23 /// @param score The score to be checked.
24 /// @return true, if the score is a highscore, and can be put on the list.
25 bool HighScoreTable::is_highscore(int score) const {
26 /* if score is above zero AND bigger than the last one */
27 if (score>0 && (table.size()<GD_HIGHSCORE_NUM || score>table.back().score))
28 return true;
30 return false;
33 /* for sorting. compares two highscores. */
34 static bool highscore_compare(const HighScore &a, const HighScore &b) {
35 return b.score>a.score;
38 #include <glib.h>
39 /// Adds a player with some score to the highscore table.
40 /// Returns the new rank.
41 /// @param name The name of the player.
42 /// @param score The score achieved.
43 /// @return The index in the table, or -1 if did not fit.
44 int HighScoreTable::add(const std::string &name, int score) {
45 if (!is_highscore(score))
46 return -1;
48 /* add to the end */
49 table.push_back(HighScore(name, score));
50 sort(table.begin(), table.end(), highscore_compare);
51 /* if too big, remove the lowest ones (after sorting) */
52 if (table.size()>GD_HIGHSCORE_NUM)
53 table.resize(GD_HIGHSCORE_NUM);
55 /* and find it so we can return an index */
56 for (unsigned int i=0; i<table.size(); i++)
57 if (table[i].name==name && table[i].score==score)
58 return i;
60 return -1;