summary refs log tree commit diff
path: root/src/save.c
blob: faeb8d1e9196e0bd5d8291a227bea23d3c5ec76b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "main.h"
#include "util.h"
#include "util.h"

void *player_new(struct entities *entities);
int player_property(void *const restrict entity, char const *const restrict property, char const *const restrict value);

int game_save(FILE *file) {
	fwrite(game_level, 1, strlen(game_level) + 1, file);
	char buf[12] = {0};
	snprintf(buf, sizeof (buf) - 1, "%i", from_fixed(entities.player[0].x));
	fwrite(buf, 1, strlen(buf) + 1, file);
	snprintf(buf, sizeof (buf) - 1, "%i", from_fixed(entities.player[0].y));
	fwrite(buf, 1, strlen(buf) + 1, file);
	fclose(file);
	return 0;
}

static char *level = NULL; // hack to not leak memory

int game_load(FILE *file) {
	size_t filesize, len;
	char *filedata = util_loadFile(file, &filesize);
	fclose(file);
	free(level);
	level = filedata;
	len = strnlen(filedata, filesize);
	if (len == filesize) {
		fputs("invalid save format\n", stderr);
		return 1;
	}
	filedata += len + 1;
	len = strnlen(filedata, filesize);
	if (len == filesize) {
		fputs("invalid save format\n", stderr);
		return 1;
	}
	player_property(next_entities.player, "x", filedata);
	filedata += len + 1;
	len = strnlen(filedata, filesize);
	if (len == filesize) {
		fputs("invalid save format\n", stderr);
		return 1;
	}
	player_property(next_entities.player, "y", filedata);
	level = realloc(level, strlen(level) + 1); // this line looks fucking stupid out of context
	return game_load_level(level);
}