hyperultra/src/game.c

124 lines
2.6 KiB
C

#include "game.h"
#include "entity.h"
#include "map.h"
#include "cfg.h"
#include "rotrect.h"
#include <string.h>
void
game_init(Game *this)
{
memset(this, 0, sizeof(*this));
this->player_dir = 1;
game_restart_scene(this);
}
void
game_deinit([[maybe_unused]] Game *this)
{
}
void
game_update(Game *this)
{
extern double tick;
this->spike_rect = rotrect_create(10, 10, tick / 16);
this->spike_irect = rotrect_create(10, 10, -tick / 16);
if (this->queue_restart_scene > 0) {
if (--this->queue_restart_scene == 0)
game_restart_scene(this);
}
if (this->queue_next_scene) {
this->queue_next_scene = false;
this->player_dir = game_get_entity(this,
entity_type("exit"))->exit.dir;
map_next();
game_restart_scene(this);
return;
}
for (int i = 0; i < MAX_ENTITIES; i++) {
Entity *const e = &this->entities[i];
if (e->type != ET_NONE && e->update != NULL)
e->update(e, this);
}
this->show_ui -= (this->show_ui > 0);
}
void
game_draw(Game *this)
{
map_draw();
for (int i = 0; i < MAX_ENTITIES; i++) {
Entity *const e = &this->entities[i];
if (e->type != ET_NONE && e->draw != NULL)
e->draw(e, this);
}
if (this->show_ui)
map_draw_ui();
}
void
game_restart_scene(Game *this)
{
memset(this->entities, 0, sizeof(this->entities));
this->show_ui = 30;
for (int y = 0; y < map_height(); y++)
for (int x = 0; x < map_width(); x++) {
const int dx = x * TSIZE + TSIZE / 2;
const int dy = y * TSIZE + TSIZE / 2;
Entity *e;
switch (map_get(x, y)) {
case 2:
e = entity_init(game_create_entity(this),
entity_type("player"), dx, dy);
e->player.dirx = this->player_dir;
break;
case 3:
case 4:
e = entity_init(game_create_entity(this),
entity_type("exit"), dx, dy);
e->exit.dir = (map_get(x, y) == 3) ? -1 : 1;
break;
case 5:
e = entity_init(game_create_entity(this),
entity_type("spike"), dx, dy);
break;
default:
break;
}
}
}
Entity *
game_create_entity(Game *this)
{
Entity *e = &this->entities[MAX_ENTITIES - 1];
for (int i = 0; i < MAX_ENTITIES; i++)
if (this->entities[i].type == ET_NONE) {
e = &this->entities[i];
break;
}
e->type = ET_NONE;
e->uuid = this->uuid;
this->uuid += 1;
return e;
}
int
game_entity_count(Game *this, unsigned int type)
{
int count = 0;
for (int i = 0; i < MAX_ENTITIES; i++)
count += (this->entities[i].type == type);
return count;
}
Entity *
game_get_entity(Game *this, unsigned int type)
{
for (int i = 0; i < MAX_ENTITIES; i++)
if (this->entities[i].type == type)
return &this->entities[i];
return NULL;
}