summaryrefslogtreecommitdiff
path: root/src/game.c
blob: 5166d9900cd3f06a6995eaef8172e115cd2d08e8 (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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#include "game.h"
#include "cfg.h"
#include "entity.h"
#include "map.h"
#include <stdio.h>
#include <string.h>

void
game_init(Game *this)
{
	memset(this, 0, sizeof(*this));
	game_restart_scene(this);
}

void
game_update(Game *this)
{
	if (this->queue_next_scene) {
		if (--this->queue_next_scene == 0) {
			this->queue_restart_scene = 0;
			this->queue_previous_scene = 0;
			map_next();
			game_restart_scene(this);
			return;
		}
	}
	if (this->queue_previous_scene) {
		if (--this->queue_next_scene == 0) {
			this->queue_restart_scene = 0;
			this->queue_next_scene = 0;
			map_previous();
			game_restart_scene(this);
			return;
		}
	}
	if (this->queue_restart_scene) {
		if (--this->queue_restart_scene == 0)
			game_restart_scene(this);
	}
	for (__auto_type i = 0; i < MAX_ENTITIES; i++) {
		const __auto_type e = &this->entities[i];
		if (e->type != 0 && e->update != NULL)
			e->update(e, this);
	}
}

void
game_draw(Game *this)
{
	map_draw();
	for (int i = 0; i < MAX_ENTITIES; i++) {
		const __auto_type e = &this->entities[i];
		if (e->type != 0 && e->draw != NULL)
			e->draw(e, this);
	}
}

void
game_restart_scene(Game *this)
{
	memset(this->entities, 0, sizeof(this->entities));
	unsigned int size;
	const __auto_type objects = map_objects(&size);
	for (__auto_type i = 0u; i < size; i++) {
		const __auto_type object = &objects[i];
		const __auto_type type = entity_type(object->type);
		if (type == 0)
			continue;
		const __auto_type x = object->x + object->width / 2;
		const __auto_type y = object->y + object->height / 2;
		entity_init(game_create_entity(this), type, object->name, x, y,
		            object->width, object->height);
	}
}

Entity *
game_create_entity(Game *this)
{
	__auto_type e = &this->entities[MAX_ENTITIES - 1];
	for (__auto_type i = 0; i < MAX_ENTITIES; i++)
		if (this->entities[i].type == 0) {
			e = &this->entities[i];
			break;
		}
	e->uuid = this->uuid++;
	return e;
}

int
game_entity_count(Game *this, unsigned int type)
{
	int count = 0;
	for (__auto_type i = 0; i < MAX_ENTITIES; i++)
		count += (this->entities[i].type == type);
	return count;
}

Entity *
game_get_entity(Game *this, unsigned int type)
{
	for (__auto_type i = 0; i < MAX_ENTITIES; i++)
		if (this->entities[i].type == type)
			return &this->entities[i];
	return NULL;
}