From: Matthew Mondor Date: Tue, 25 Apr 2023 17:09:14 +0000 (+0000) Subject: Load/Save high score from/to file. X-Git-Url: http://git.pulsar-zone.net/?a=commitdiff_plain;h=750b5ee6b8abc3aa092d7bc4296decce68b21a30;p=pacman.git Load/Save high score from/to file. --- diff --git a/pacman.c b/pacman.c index d84d2bb..6ec6b1c 100755 --- a/pacman.c +++ b/pacman.c @@ -49,12 +49,19 @@ void MovePacman(void); //Update Pacman's locati void PauseGame(void); //Pause void PrintHelp(char* name); //Print help and exit int GameOverScreen(void); +void HighScoreInit(void); +void HighScoreLoad(void); +void HighScoreSave(void); + /******************* * GLOBAL VARIABLES * *******************/ //I know global variables are bad, but it's just sooo easy! +//File to load/save high score +char *highscorefullpath = NULL; + //Windows used by curses WINDOW * win; WINDOW * status; @@ -123,6 +130,9 @@ int main(int argc, char *argv[100]) { srand( (unsigned)time( NULL ) ); + HighScoreInit(); + HighScoreLoad(); + InitCurses(); //Must be called to start curses CheckScreenSize(); //Make sure screen is big enough CreateWindows(30, 28, 1, 1); //Create the main and status windows @@ -263,6 +273,7 @@ int GameOverScreen(void) { if (Points > HiPoints) { HiPoints = Points; HiLevelNumber = LevelNumber; + HighScoreSave(); } werase(win); @@ -866,3 +877,64 @@ void PrintHelp(char* name) { printf(" --level=LEVEL play specified non-standard LEVEL\n"); } + +#define HIGHSCOREFULLPATHBUFSIZ 256 + +void HighScoreInit(void) +{ + char *home; + + if (highscorefullpath != NULL) + return; + + if ((highscorefullpath = malloc(HIGHSCOREFULLPATHBUFSIZ)) == NULL) + goto err; + if ((home = getenv("HOME")) == NULL) + goto err; + (void)snprintf(highscorefullpath, HIGHSCOREFULLPATHBUFSIZ - 1, + "%s/%s", home, HIGHSCORE_FILE); + highscorefullpath[HIGHSCOREFULLPATHBUFSIZ - 1] = '\0'; + + return; +err: + if (highscorefullpath != NULL) { + free(highscorefullpath); + highscorefullpath = NULL; + } +} + +void HighScoreLoad(void) +{ + FILE *fh; + char line[64]; + + if (highscorefullpath == NULL) + return; + + if ((fh = fopen(highscorefullpath, "r")) != NULL) { + if (fgets(line, 63, fh) != NULL) { + line[63] = '\0'; + HiPoints = atoi(line); + } + if (fgets(line, 63, fh) != NULL) { + line[63] = '\0'; + HiLevelNumber = atoi(line); + } + (void)fclose(fh); + } +} + +/* XXX Should ideally save in a new unique file and rename for safety */ +void HighScoreSave(void) +{ + FILE *fh; + + if (highscorefullpath == NULL) + return; + + if ((fh = fopen(highscorefullpath, "w")) != NULL) { + (void)fprintf(fh, "%d\n", HiPoints); + (void)fprintf(fh, "%d\n", HiLevelNumber); + (void)fclose(fh); + } +} diff --git a/pacman.h b/pacman.h index db027f0..1ed88c0 100755 --- a/pacman.h +++ b/pacman.h @@ -10,3 +10,4 @@ int Points = 0; //Initial points int Lives = 3; //Number of lives you start with int HowSlow = 3; //How slow vulnerable ghost move #define FPS 5 +#define HIGHSCORE_FILE ".pacman_highscore"