Merge pull request #4 from AMDmi3/highscore-handling
Fix highscore file handling
This commit is contained in:
commit
5781fc6c16
8
Makefile
8
Makefile
|
@ -4,11 +4,11 @@ LIBS = -lcurses
|
|||
|
||||
all: 2048
|
||||
|
||||
2048: src/2048.c
|
||||
$(CC) $(CFLAGS) src/2048.c -o 2048 $(LIBS)
|
||||
2048: src/2048.c src/2048.h src/highscore_file.c
|
||||
$(CC) $(CFLAGS) src/2048.c src/highscore_file.c -o 2048 $(LIBS)
|
||||
|
||||
2048nc: src/2048_no_curses.c
|
||||
$(CC) $(CFLAGS) src/2048_no_curses.c -o 2048nc
|
||||
2048nc: src/2048_no_curses.c src/2048.h src/highscore_file.c
|
||||
$(CC) $(CFLAGS) src/2048_no_curses.c src/highscore_file.c -o 2048nc
|
||||
|
||||
clean:
|
||||
rm -f 2048 2048nc
|
||||
|
|
11
src/2048.h
11
src/2048.h
|
@ -1,6 +1,10 @@
|
|||
#ifndef _2048_H_
|
||||
#define _2048_H_
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <sys/stat.h>
|
||||
#include <string.h>
|
||||
|
||||
typedef enum {
|
||||
DIR_UP,
|
||||
DIR_RIGHT,
|
||||
|
@ -8,6 +12,11 @@ typedef enum {
|
|||
DIR_LEFT
|
||||
} dir_t;
|
||||
|
||||
#define DATADIR_NAME "2048"
|
||||
#define HIGHSCORE_FILE_NAME "highscore"
|
||||
|
||||
const char* get_highscore_file();
|
||||
|
||||
// Repeat an expression y, x times */
|
||||
#define ITER(x, expr)\
|
||||
do {\
|
||||
|
@ -38,7 +47,7 @@ typedef enum {
|
|||
|
||||
/* Constants */
|
||||
#define DEFAULT_GRID_SIZE 4
|
||||
#define HISCORE_FILE ".hs2048g"
|
||||
#define HISCORE_FILE get_highscore_file()
|
||||
#define USAGE_STR\
|
||||
"Usage:\n"\
|
||||
" ./2048 [options]\n"\
|
||||
|
|
29
src/highscore_file.c
Normal file
29
src/highscore_file.c
Normal file
|
@ -0,0 +1,29 @@
|
|||
#include "2048.h"
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <sys/stat.h>
|
||||
#include <string.h>
|
||||
#include <stdio.h>
|
||||
|
||||
const char* get_highscore_file() {
|
||||
static char buffer[4096];
|
||||
if (getenv("XDG_DATA_HOME") != NULL) {
|
||||
snprintf(buffer, sizeof(buffer), "%s/%s/%s", getenv("XDG_DATA_HOME"), DATADIR_NAME, HIGHSCORE_FILE_NAME);
|
||||
} else if (getenv("HOME") != NULL) {
|
||||
snprintf(buffer, sizeof(buffer), "%s/.local/share/%s/%s", getenv("HOME"), DATADIR_NAME, HIGHSCORE_FILE_NAME);
|
||||
} else {
|
||||
return HIGHSCORE_FILE_NAME;
|
||||
}
|
||||
|
||||
// create hierarrchy of directories up to highscore file location
|
||||
char* sep = strrchr(buffer, '/');
|
||||
while (sep != NULL) {
|
||||
*sep = '\0';
|
||||
if (strlen(buffer) != 0)
|
||||
mkdir(buffer, 0777);
|
||||
char* tmpsep = sep;
|
||||
sep = strrchr(buffer, '/');
|
||||
*tmpsep = '/';
|
||||
}
|
||||
return buffer;
|
||||
}
|
Loading…
Reference in New Issue
Block a user