Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <string.h>
- #include "highscoretable.h"
- HighscoreTable::HighscoreTable()
- {/*{{{*/
- // this is the initialization of the class. Here, you could,
- // for example, read from a text file, and use that to populate
- // the scores array. For demo purposes, though, I'm gonna generate a silly default table
- int i;
- for(i = 0; i < 5; i++){
- scores[i] = new HighscoreEntry();
- scores[i]->score = (i+1) * 100;
- }
- strcpy(scores[0]->name, "AAA");
- strcpy(scores[1]->name, "BBB");
- strcpy(scores[2]->name, "CCC");
- strcpy(scores[3]->name, "DDD");
- strcpy(scores[4]->name, "EEE");
- }/*}}}*/
- HighscoreTable::~HighscoreTable()
- {/*{{{*/
- int i;
- for(i = 0; i < 5; i++){
- delete scores[i];
- }
- }/*}}}*/
- void
- HighscoreTable::insert(int score, const char *name)
- {/*{{{*/
- int lowestID = getLowest();
- HighscoreEntry *lowest = scores[lowestID];
- if(score > lowest->score){
- lowest->score = score;
- strcpy(lowest->name, name);
- }
- }/*}}}*/
- int
- HighscoreTable::getLowest()
- {/*{{{*/
- int i,
- lowest = scores[0]->score,
- lowestID = 0,
- temp;
- for(i = 1; i < 5; i++){
- temp = scores[i]->score;
- if(temp < lowest){
- lowest = temp;
- lowestID = i;
- }
- }
- return lowestID;
- }/*}}}*/
- void
- HighscoreTable::swap(int a, int b)
- {/*{{{*/
- HighscoreEntry *temp = scores[a];
- scores[a] = scores[b];
- scores[b] = temp;
- }/*}}}*/
- void
- HighscoreTable::sort()
- {/*{{{*/
- // This is a neat sorting algorithm called bubble sort. Look it up
- int i,
- j,
- needsSort;
- for(i = 0; i < 5; i++){
- needsSort = false;
- for(j = 4; j > i; j--){
- if(scores[j]->score > scores[j-1]->score){
- swap(j, j-1);
- needsSort = true;
- }
- }
- if(!needsSort){
- break;
- }
- }
- }/*}}}*/
- const char *
- HighscoreTable::getRankStr(int rank)
- {/*{{{*/
- switch(rank){
- case 1: return "st";
- case 2: return "nd";
- case 3: return "rd";
- default: return "th";
- }
- }/*}}}*/
- void
- HighscoreTable::reportRow(int rank)
- {/*{{{*/
- HighscoreEntry *row = scores[rank];
- printf("%i%s \t%i\t %s\n", rank + 1, getRankStr(rank + 1), row->score, row->name);
- }/*}}}*/
- void
- HighscoreTable::report()
- {/*{{{*/
- int i;
- sort();
- printf("Rank\tScore\tName\n");
- for(i = 0; i < 5; i++){
- reportRow(i);
- }
- }/*}}}*/
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement