Changed file write/load to support more sizes.

This commit is contained in:
Sheldon Lee 2020-07-06 22:28:47 +01:00
parent 5972ed4b13
commit 031393a7b3

46
game.c
View File

@ -136,48 +136,42 @@ void drawCurPos()
void saveGame(char* name) void saveGame(char* name)
{ {
unsigned int width, height;
getDimensions(grid, &width, &height);
FILE* file = NULL; FILE* file = NULL;
file = fopen(name, "w"); file = fopen(name, "w");
if (!file) {
fprintf(file, "%c%c", width, height); logLine("Failed to write file.");
if (file) { return;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
fprintf(file, "%i", getPixel(grid, x, y));
}
}
fclose(file);
} }
unsigned int dimensions[2] = {grid->width, grid->size};
fwrite(dimensions, sizeof(dimensions), 1, file);
fwrite(grid->state, sizeof(bool), grid->size, file);
fclose(file);
} }
void loadGame(char* name) void loadGame(char* name)
{ {
FILE* file = NULL; FILE* file = NULL;
file = fopen(name, "r"); file = fopen(name, "r");
if (!file) return; if (!file) {
logLine("Failed to load file.");
return;
}
if (!grid) initGame(); if (!grid) initGame();
else clearGrid(grid); else clearGrid(grid);
unsigned int width, height; unsigned int width, height, size;
bool* pixels; bool* pixels;
int count = 0;
char c;
unsigned int size;
width = (unsigned int)fgetc(file); height = (unsigned int)fgetc(file); fread(&width, sizeof(unsigned int), 1, file);
size = width * height; fread(&size, sizeof(unsigned int), 1, file);
pixels = (bool*)malloc(sizeof(char)*size); height = size/width;
pixels = (bool*)malloc(sizeof(bool)*size);
fread(pixels, sizeof(bool), size, file);
while((c = fgetc(file)) != EOF) {
pixels[count] = (c == '1');
count++;
}
unsigned int grid_width, grid_height; unsigned int grid_width, grid_height;
getDimensions(grid, &grid_width, &grid_height); getDimensions(grid, &grid_width, &grid_height);
for (int y =0; y < min(grid_height, height); y++) { for (int y =0; y < min(grid_height, height); y++) {