1
1
Fork 0
Browse Source

serializing controlscheme

master
alistair 3 years ago
parent
commit
c40e2a770a
  1. 78
      src/controlscheme.c
  2. 1
      src/controlscheme.h
  3. 15
      src/main.c

78
src/controlscheme.c

@ -1,10 +1,28 @@ @@ -1,10 +1,28 @@
#include "controlscheme.h"
#include <SDL2/SDL_scancode.h>
#include <sys/stat.h>
struct InputMap input_map;
#define INPUT_MAP_ID 83921864
#define INPUT_MAP_VERSION 0
#define CONTROLS_FNAME "controls.bin"
struct InputMap_Ser {
unsigned int id;
unsigned int ver;
struct InputMap input_map;
};
int load_controls(void);
void get_input_map(void) {
if (load_controls()) {
return;
}
input_map.player_down = SDL_SCANCODE_S;
input_map.player_up = SDL_SCANCODE_W;
input_map.player_right = SDL_SCANCODE_D;
@ -16,3 +34,63 @@ void get_input_map(void) { @@ -16,3 +34,63 @@ void get_input_map(void) {
input_map.quit = SDL_SCANCODE_Q;
}
struct Buffer {
size_t len;
char *data;
};
struct Buffer read_whole_file(char const *file_name) {
struct stat sb;
struct Buffer b = {};
if (stat (file_name, & sb) != 0) {
return b;
}
char *buffer = malloc(sb.st_size + 1);
FILE *f = fopen(file_name, "r");
size_t bytes_read = fread(buffer, sizeof (unsigned char), sb.st_size, f);
if (bytes_read != sb.st_size) {
fclose(f);
free(buffer);
return b;
}
fclose(f);
b.data = buffer;
b.len = bytes_read;
return b;
}
int load_controls(void) {
struct Buffer b = read_whole_file(CONTROLS_FNAME);
if (b.len != sizeof (struct InputMap_Ser)) {
return 0;
}
struct InputMap_Ser *im = (struct InputMap_Ser *)b.data;
if (im->id != INPUT_MAP_ID)
return 0;
if (im->ver != INPUT_MAP_VERSION)
return 0;
memcpy(&input_map, &im->input_map, sizeof(struct InputMap));
return 1;
}
void save_controls(void) {
FILE *f = fopen(CONTROLS_FNAME, "w");
struct InputMap_Ser im;
im.id = INPUT_MAP_ID;
im.ver = INPUT_MAP_VERSION;
im.input_map = input_map;
fwrite(&im, sizeof(unsigned char), sizeof(struct InputMap_Ser), f);
fclose(f);
}

1
src/controlscheme.h

@ -25,6 +25,7 @@ struct InputMap { @@ -25,6 +25,7 @@ struct InputMap {
extern struct InputMap input_map;
void get_input_map(void);
void save_controls(void);
#endif

15
src/main.c

@ -72,6 +72,8 @@ int physics_loop(void *ptr) { @@ -72,6 +72,8 @@ int physics_loop(void *ptr) {
}
}
int game(void) {
//SDL_SetHint( SDL_HINT_RENDER_SCALE_QUALITY, "2" );
@ -161,3 +163,16 @@ int main (int argc, char** argv) { @@ -161,3 +163,16 @@ int main (int argc, char** argv) {
return 0;
}
/*
* TODO:
* - Allow setting and saving/loading differnet control schemes
* - Allow starting a specific level
* - Allow adjusging level lengths?
* - Ensure next_level doesn't leak memory
* - fix that weird jitter
* - make the end of level look sane
* - restart level
*/

Loading…
Cancel
Save