1 #include <string.h>
2 #include <stdlib.h>
3 #include <stdio.h>
4 #include "preferences.h"
5 #include "HiScores.h"
6 
7 static hiscore HS[kHiScoresNumber];
8 static bool loaded = false;
9 
initHiScores(const char * const defaultNames[kHiScoresNumber])10 void initHiScores(const char * const defaultNames[kHiScoresNumber])
11 {
12     char HSID[8];
13 
14     for (int i=0; i<kHiScoresNumber; i++)
15     {
16         sprintf(HSID,"HSN%2d",i);
17         GetStrPreference(HSID,HS[i].name,defaultNames[kHiScoresNumber-i-1],kHiScoreNameLenght+1);
18         sprintf(HSID,"HSS%2d",i);
19         HS[i].score = GetIntPreference(HSID,(kHiScoresNumber-i) * 10000);
20     }
21     loaded = true;
22 }
23 
getHiScores(void)24 hiscore * getHiScores(void)
25 {
26     if (loaded!=true)
27     {
28         fprintf(stderr,"getHiscores() called before init, app may crash...");
29         return NULL;
30     }
31     else return  HS;
32 }
33 
34 
35 
36 
setHiScore(int score,const char * name)37 int setHiScore(int score, const char * name)
38 {
39   int retour = -1;
40 
41   if (loaded!=true)
42   {
43     fprintf(stderr,"setHiscores() called before init, app may crash...");
44     return retour;
45   }
46 
47   hiscore * tmp = (hiscore*)malloc(sizeof(hiscore));
48   hiscore * tmp2= (hiscore*)malloc(sizeof(hiscore));
49 
50   if ((tmp==NULL) || (tmp2 == NULL))
51   {
52     fprintf(stderr,"Malloc failed, I won't save your score...");
53     return retour;
54   }
55 
56   strncpy(tmp->name,name,kHiScoreNameLenght);
57   tmp->name[kHiScoreNameLenght]=0;
58   tmp->score = score;
59 
60   char HSID[8];
61 
62   for (int i=0; i<kHiScoresNumber; i++)
63   {
64     if (tmp->score >= HS[i].score)
65     {
66       if (retour == -1) retour = i;
67 
68       sprintf(HSID,"HSN%2d",i);
69       SetStrPreference(HSID,tmp->name);
70       sprintf(HSID,"HSS%2d",i);
71       SetIntPreference(HSID,tmp->score);
72 
73       memcpy(tmp2,&(HS[i]),sizeof(hiscore));
74       memcpy(&(HS[i]),tmp,sizeof(hiscore));
75       memcpy(tmp,tmp2,sizeof(hiscore));
76     }
77   }
78 
79   free(tmp);
80   free(tmp2);
81 
82   return retour;
83 }
84