Skip to content

Instantly share code, notes, and snippets.

@ivxvm
Created Jun 13, 2020
Embed
What would you like to do?
struct game_manager {
struct rng rng;
struct sprite_atlas atlas;
struct scene scene;
struct creature player;
struct input_manager input_manager;
};
void game_manager_init(struct game_manager* self) {
srand(time(NULL));
rng_init(&self->rng, rand());
sprite_atlas_init(&self->atlas, "/data/Assets/...tileset.v4.png", 16, 16);
creature_init(&self->player, 161);
scene_init(&self->scene, &self->rng, &self->player, 15, 20);
input_manager_init(&self->input_manager);
event_emitter_subscribe(&self->input_manager.events,
self, (void (*)(void*, void*, void*))game_manager_handle_event);
event_emitter_subscribe(&self->player.events,
self, (void (*)(void*, void*, void*))game_manager_handle_event);
}
// ...other game_manager stuff...
void game_manager_free(struct game_manager* self) {
creature_free(&self->player);
scene_free(&self->scene);
sprite_atlas_free(&self->atlas);
input_manager_free(&self->input_manager);
}
/////////////////////////////////////////////////////////////////////////////
struct input_manager {
bool is_movement_input_present;
enum direction movement_input_direction;
struct event_emitter events;
};
void input_manager_init(struct input_manager* self) {
self->is_movement_input_present = false;
self->movement_input_direction = DIR_NONE;
event_emitter_init(&self->events);
}
// ...other input_manager stuff...
void input_manager_free(struct input_manager* self) {
event_emitter_free(&self->events);
}
////////////////////////////////////////////////////////////////////////////
struct event_emitter_listener {
void (*callback)(void*, void*, void*);
void *context;
};
struct event_emitter {
int listeners_count;
struct event_emitter_listener* listeners;
};
void event_emitter_init(struct event_emitter* self) {
self->listeners_count = 0;
self->listeners = malloc(2 * sizeof(struct event_emitter_listener));
}
void event_emitter_subscribe(struct event_emitter* self, void* context, void (*callback)(void*, void*, void*)) {
int n = self->listeners_count;
if (n > 0 && (n & (n - 1)) == 0) {
self->listeners = realloc(self->listeners, 2 * n * sizeof(struct event_emitter_listener));
}
self->listeners[self->listeners_count] = (struct event_emitter_listener) {
.callback = callback,
.context = context,
};
self->listeners_count++;
}
void event_emitter_emit(struct event_emitter* self, void* sender, void* event) {
for (int i = 0; i < self->listeners_count; i++) {
struct event_emitter_listener* listener = &self->listeners[i];
listener->callback(listener->context, sender, event);
}
}
void event_emitter_free(struct event_emitter* self) {
free(self->listeners);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment