diff --git a/src/player.c b/src/player.c index 8ede7a9..bee1fb8 100644 --- a/src/player.c +++ b/src/player.c @@ -6,7 +6,7 @@ * Saves a player file to the specified path. Returns 0 on success, non-zero on * failure. */ -int Player_save (Player *player, char *path) { +int Player_save (Player *player, const char *path) { FILE *file = fopen(path, "w"); if (file == NULL) { return 1; } @@ -16,13 +16,12 @@ int Player_save (Player *player, char *path) { "%a %a %a\n" "%a %a\n" "%hhu %hhu %hhu\n" - "%i\n", + "%hu\n", 0, player->pos.x, player->pos.y, player->pos.z, player->hRot, player->vRot, player->health, player->hunger, player->breath, - player->xp - ); + player->xp); // TODO: save inventory @@ -31,6 +30,37 @@ int Player_save (Player *player, char *path) { return 0; } +/* Player_save + * Loads a player from the specified file. Returns 0 on success, non-zero on + * failure. + */ +int Player_load (Player *player, const char *path) { + FILE *file = fopen(path, "r"); + if (file == NULL) { return 1; } + + int version; + fscanf(file, "%i", &version); + if (version != 0) { return 2; } + + fscanf ( + file, + "%a %a %a " + "%a %a " + "%hhu %hhu %hhu " + "%hu", + &player->pos.x, &player->pos.y, &player->pos.z, + &player->hRot, &player->vRot, + &player->health, &player->hunger, &player->breath, + &player->xp + ); + + // TODO: load inventory + + fclose(file); + + return 0; +} + /* Inventory_transferIn * Transfers items from src int dest. This will transfer as many items as it * can. Returns true if all items were transferred, false if some items weren't. diff --git a/src/player.h b/src/player.h index 67034c7..35cf0cf 100644 --- a/src/player.h +++ b/src/player.h @@ -56,4 +56,5 @@ typedef struct Player { float LRVelocity; } Player; -int Player_save (Player *, char *); +int Player_save (Player *, const char *); +int Player_load (Player *, const char *); diff --git a/src/terrain.c b/src/terrain.c index a3ef382..236a93d 100644 --- a/src/terrain.c +++ b/src/terrain.c @@ -61,7 +61,7 @@ int World_save (World *world) { data_getWorldPlayerPath ( playerPath, world->path, data_options.username.buffer); - Player_save(&world->player, playerPath); + if (Player_save(&world->player, playerPath)) { return 3; } return 0; } @@ -110,11 +110,19 @@ int World_load (World *world, const char *name) { fclose(metadata); - world->player = (const Player) { 0 }; - world->player.pos.x = 32.5; - world->player.pos.y = 16; - world->player.pos.z = 32.5; - + char playerPath[PATH_MAX]; + data_getWorldPlayerPath ( + playerPath, world->path, + data_options.username.buffer); + if (data_fileExists(playerPath)) { + Player_load(&world->player, playerPath); + } else { + world->player = (const Player) { 0 }; + world->player.pos.x = 32.5; + world->player.pos.y = 64; + world->player.pos.z = 32.5; + } + return 0; }